import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";

const VALID_CATEGORIES = [
  "product",
  "feature",
  "service",
  "event",
  "help",
  "general",
];

/**
 * GET /api/waitlists
 * List waitlists:
 * - If ?mine=true: Returns user's own waitlists (requires auth)
 * - Otherwise: Returns public/system waitlists that are active
 */
export async function GET(request: NextRequest) {
  try {
    // Support both NextAuth and OTP auth_token authentication
    const authenticatedUser = await getAuthenticatedUser(request, auth);
    const userId = authenticatedUser?.userId;
    const { searchParams } = new URL(request.url);
    const showMine = searchParams.get("mine") === "true";

    // If requesting user's own waitlists
    if (showMine) {
      if (!userId) {
        return NextResponse.json(
          { error: "Authentication required" },
          { status: 401 },
        );
      }

      const userWaitlists = await prisma.waitlists.findMany({
        where: { userId },
        orderBy: { createdAt: "desc" },
        include: {
          _count: {
            select: { signups: true },
          },
        },
      });

      const formattedWaitlists = userWaitlists.map((w) => ({
        id: w.id,
        title: w.title,
        titleAr: w.titleAr,
        description: w.description,
        descriptionAr: w.descriptionAr,
        category: w.category,
        isActive: w.isActive,
        isPublic: w.isPublic,
        createdAt: w.createdAt,
        updatedAt: w.updatedAt,
        signupCount: w._count.signups,
        isOwner: true,
      }));

      return NextResponse.json({
        waitlists: formattedWaitlists,
        total: formattedWaitlists.length,
      });
    }

    // Otherwise, return public/system waitlists that are active
    const waitlists = await prisma.waitlists.findMany({
      where: {
        isActive: true,
        OR: [
          { isPublic: true },
          { userId: null }, // System/staff created waitlists
        ],
      },
      orderBy: { createdAt: "desc" },
      select: {
        id: true,
        title: true,
        titleAr: true,
        description: true,
        descriptionAr: true,
        category: true,
        createdAt: true,
        _count: {
          select: { signups: true },
        },
      },
    });

    // If user is logged in, check which waitlists they've signed up for
    let userSignups: Set<string> = new Set();
    if (userId) {
      const signups = await prisma.waitlist_signups.findMany({
        where: { userId },
        select: { waitlistId: true },
      });
      userSignups = new Set(signups.map((s) => s.waitlistId));
    }

    const formattedWaitlists = waitlists.map((w) => ({
      id: w.id,
      title: w.title,
      titleAr: w.titleAr,
      description: w.description,
      descriptionAr: w.descriptionAr,
      category: w.category,
      createdAt: w.createdAt,
      signupCount: w._count.signups,
      isSignedUp: userSignups.has(w.id),
    }));

    return NextResponse.json({
      waitlists: formattedWaitlists,
    });
  } catch (error) {
    console.error("Failed to fetch waitlists:", error);
    return NextResponse.json(
      { error: "Failed to fetch waitlists" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/waitlists
 * Create a new waitlist (requires authentication)
 */
export async function POST(request: NextRequest) {
  try {
    // Support both NextAuth and OTP auth_token authentication
    const authenticatedUser = await getAuthenticatedUser(request, auth);
    if (!authenticatedUser?.userId) {
      return NextResponse.json(
        { error: "Authentication required" },
        { status: 401 },
      );
    }

    const userId = authenticatedUser.userId;
    const body = await request.json();
    const {
      title,
      titleAr,
      description,
      descriptionAr,
      category = "general",
      isActive = true,
      isPublic = false,
    } = body;

    // Validate title
    if (!title || typeof title !== "string" || title.trim().length === 0) {
      return NextResponse.json({ error: "Title is required" }, { status: 400 });
    }

    // Validate category
    const normalizedCategory = VALID_CATEGORIES.includes(category)
      ? category
      : "general";

    const id = createId();

    const waitlist = await prisma.waitlists.create({
      data: {
        id,
        title: title.trim(),
        titleAr: titleAr?.trim() || null,
        description: description?.trim() || null,
        descriptionAr: descriptionAr?.trim() || null,
        category: normalizedCategory,
        isActive,
        isPublic,
        userId,
        createdBy: userId,
      },
    });

    return NextResponse.json({
      success: true,
      waitlist: {
        id: waitlist.id,
        title: waitlist.title,
        titleAr: waitlist.titleAr,
        description: waitlist.description,
        descriptionAr: waitlist.descriptionAr,
        category: waitlist.category,
        isActive: waitlist.isActive,
        isPublic: waitlist.isPublic,
        createdAt: waitlist.createdAt,
        signupCount: 0,
      },
    });
  } catch (error) {
    console.error("Failed to create waitlist:", error);
    return NextResponse.json(
      { error: "Failed to create waitlist" },
      { status: 500 },
    );
  }
}
