import { Router, type IRouter } from "express";
import { db, bookingsTable, profilesTable, locationsTable, membershipsTable } from "@workspace/db";
import { eq, count, and } from "drizzle-orm";
import { requireAuth } from "../middlewares/auth";

const router: IRouter = Router();

router.get("/dashboard/summary", requireAuth, async (req, res): Promise<void> => {
  const userId = req.user!.id;

  const [bookingsCount] = await db.select({ count: count() }).from(bookingsTable).where(eq(bookingsTable.userId, userId));
  const [activeBookings] = await db.select({ count: count() }).from(bookingsTable).where(
    and(eq(bookingsTable.userId, userId), eq(bookingsTable.status, "pending"))
  );
  const [profilesCount] = await db.select({ count: count() }).from(profilesTable).where(eq(profilesTable.isActive, true));
  const [locationsCount] = await db.select({ count: count() }).from(locationsTable).where(eq(locationsTable.isActive, true));

  const [membership] = await db.select().from(membershipsTable).where(eq(membershipsTable.userId, userId));

  res.json({
    totalBookings: Number(bookingsCount?.count ?? 0),
    activeBookings: Number(activeBookings?.count ?? 0),
    membershipLevel: membership?.tier ?? "free",
    profilesCount: Number(profilesCount?.count ?? 0),
    locationsCount: Number(locationsCount?.count ?? 0),
  });
});

router.get("/dashboard/featured-profiles", requireAuth, async (req, res): Promise<void> => {
  const profiles = await db.select().from(profilesTable).where(
    and(eq(profilesTable.isFeatured, true), eq(profilesTable.isActive, true))
  ).limit(6);
  res.json(profiles.map(p => ({
    id: p.id, profileId: p.profileId, name: p.name, city: p.city,
    photoUrl: p.photoUrl, bio: p.bio, isFeatured: p.isFeatured, isActive: p.isActive,
    tags: p.tags, createdAt: p.createdAt,
  })));
});

router.get("/dashboard/featured-locations", requireAuth, async (req, res): Promise<void> => {
  const locations = await db.select().from(locationsTable).where(
    and(eq(locationsTable.isFeatured, true), eq(locationsTable.isActive, true))
  ).limit(6);
  res.json(locations.map(l => ({
    id: l.id, name: l.name, city: l.city, type: l.type, rating: l.rating,
    photoUrl: l.photoUrl, description: l.description, address: l.address,
    isFeatured: l.isFeatured, isActive: l.isActive, createdAt: l.createdAt,
  })));
});

router.get("/dashboard/recent-activity", requireAuth, async (req, res): Promise<void> => {
  const userId = req.user!.id;
  const bookings = await db.select({
    booking: bookingsTable,
    profileName: profilesTable.name,
    locationName: locationsTable.name,
  }).from(bookingsTable)
    .leftJoin(profilesTable, eq(bookingsTable.profileId, profilesTable.id))
    .leftJoin(locationsTable, eq(bookingsTable.locationId, locationsTable.id))
    .where(eq(bookingsTable.userId, userId))
    .orderBy(bookingsTable.createdAt)
    .limit(10);

  res.json(bookings.map(({ booking, profileName, locationName }) => ({
    id: booking.id, userId: booking.userId, profileId: booking.profileId,
    locationId: booking.locationId, profileName, locationName,
    status: booking.status, notes: booking.notes,
    scheduledAt: booking.scheduledAt, createdAt: booking.createdAt,
  })));
});

export default router;
