import { Router, type IRouter } from "express";
import { db, profilesTable } from "@workspace/db";
import { eq, and, ilike, or } from "drizzle-orm";
import { requireAuth } from "../middlewares/auth";
import { ListProfilesQueryParams, GetProfileParams, CreateModelApplicationBody } from "@workspace/api-zod";
import { serializeProfile, insertProfileWithGeneratedId } from "../lib/profile";

const router: IRouter = Router();

router.get("/profiles", requireAuth, async (req, res): Promise<void> => {
  const params = ListProfilesQueryParams.safeParse(req.query);

  const filters = [eq(profilesTable.isActive, true), eq(profilesTable.approvalStatus, "approved")];
  if (params.success && params.data.city) {
    filters.push(ilike(profilesTable.city, `%${params.data.city}%`));
  }
  if (params.success && params.data.search) {
    const s = `%${params.data.search}%`;
    const profiles = await db.select().from(profilesTable).where(
      and(
        eq(profilesTable.isActive, true),
        eq(profilesTable.approvalStatus, "approved"),
        or(ilike(profilesTable.name, s), ilike(profilesTable.city, s), ilike(profilesTable.bio ?? "", s))
      )
    );
    res.json(profiles.map(serializeProfile));
    return;
  }

  const profiles = await db.select().from(profilesTable).where(and(...filters));
  res.json(profiles.map(serializeProfile));
});

router.post("/profiles", requireAuth, async (req, res): Promise<void> => {
  const parsed = CreateModelApplicationBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }
  const d = parsed.data;

  const existing = await db.select().from(profilesTable).where(eq(profilesTable.userId, req.user!.id));
  const active = existing.find((p) => p.approvalStatus !== "rejected");
  if (active) {
    res.status(409).json({ error: "You already have a model application." });
    return;
  }

  const profile = await insertProfileWithGeneratedId({
    userId: req.user!.id,
    name: d.name,
    city: d.city,
    proStatus: d.proStatus,
    price1h: d.price1h,
    price2h: d.price2h,
    priceFullDay: d.priceFullDay,
    services: d.services,
    photoUrl: d.photoUrl ?? undefined,
    bio: d.bio ?? undefined,
    contactPlatform: d.contactPlatform ?? "whatsapp",
    whatsappNumber: d.whatsappNumber,
    approvalStatus: "pending",
  });

  res.status(201).json(serializeProfile(profile));
});

router.get("/profiles/:id", requireAuth, async (req, res): Promise<void> => {
  const params = GetProfileParams.safeParse({ id: req.params.id });
  if (!params.success) {
    res.status(400).json({ error: "Invalid ID" });
    return;
  }
  const [profile] = await db.select().from(profilesTable).where(eq(profilesTable.id, params.data.id));
  if (!profile) {
    res.status(404).json({ error: "Profile not found" });
    return;
  }
  const isApproved = profile.approvalStatus === "approved" && profile.isActive;
  const isOwner = profile.userId != null && profile.userId === req.user!.id;
  const isAdmin = req.user!.role === "admin";
  if (!isApproved && !isOwner && !isAdmin) {
    res.status(404).json({ error: "Profile not found" });
    return;
  }
  res.json(serializeProfile(profile));
});

export default router;
