import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";
import { getDataSource } from "@/lib/data-source";

/**
 * GET /api/staff/dashboard/waitlists
 * List all waitlists with signup counts
 */
export async function GET(request: NextRequest) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const includeInactive = searchParams.get("includeInactive") === "true";

    // Convex branch
    if (getDataSource("leads") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const waitlists = (await convexQuery("bookings/queries:getWaitlists", {
          includeInactive,
        })) as any[];

        if (waitlists) {
          const formattedWaitlists = await Promise.all(
            waitlists.map(async (w: any) => {
              const signupsResult = (await convexQuery(
                "bookings/queries:getWaitlistSignups",
                {
                  waitlistId: w._id,
                  limit: 0,
                },
              )) as any;
              return {
                id: w._id,
                title: w.title,
                titleAr: w.titleAr,
                description: w.description,
                descriptionAr: w.descriptionAr,
                category: w.category,
                isActive: w.isActive,
                createdBy: w.createdBy,
                createdAt: new Date(w.createdAt).toISOString(),
                updatedAt: new Date(w.updatedAt).toISOString(),
                signupCount: signupsResult?.total ?? 0,
              };
            }),
          );

          return NextResponse.json({
            waitlists: formattedWaitlists,
            total: formattedWaitlists.length,
          });
        }
      } catch (convexError) {
        console.error(
          "Convex waitlists fetch failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    const where = includeInactive ? {} : { isActive: true };

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

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

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

/**
 * POST /api/staff/dashboard/waitlists
 * Create a new waitlist
 */
export async function POST(request: NextRequest) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

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

    // Validate category
    const validCategories = [
      "product",
      "feature",
      "service",
      "event",
      "help",
      "general",
    ];
    const normalizedCategory = validCategories.includes(category)
      ? category
      : "general";

    // Convex branch
    if (getDataSource("leads") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const convexId = await convexMutation(
          "bookings/mutations:createWaitlist",
          {
            title: title.trim(),
            titleAr: titleAr?.trim() || undefined,
            description: description?.trim() || undefined,
            descriptionAr: descriptionAr?.trim() || undefined,
            category: normalizedCategory,
            isActive,
            createdBy: staffUser.id,
          },
        );

        return NextResponse.json({
          success: true,
          waitlist: {
            id: convexId,
            title: title.trim(),
            titleAr: titleAr?.trim() || null,
            description: description?.trim() || null,
            descriptionAr: descriptionAr?.trim() || null,
            category: normalizedCategory,
            isActive,
            createdBy: staffUser.id,
          },
        });
      } catch (convexError) {
        console.error(
          "Convex waitlist create failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    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,
        createdBy: staffUser.id,
      },
    });

    return NextResponse.json({
      success: true,
      waitlist,
    });
  } catch (error) {
    console.error("Failed to create waitlist:", error);
    return NextResponse.json(
      { error: "Failed to create waitlist" },
      { status: 500 },
    );
  }
}
