import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";

interface RouteParams {
  params: { id: string };
}

/**
 * GET /api/staff/dashboard/waitlists/[id]
 * Get a single waitlist with signups
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = params;

    const waitlist = await prisma.waitlists.findUnique({
      where: { id },
      include: {
        signups: {
          orderBy: { createdAt: "desc" },
          take: 100,
        },
        _count: {
          select: { signups: true },
        },
      },
    });

    if (!waitlist) {
      return NextResponse.json(
        { error: "Waitlist not found" },
        { status: 404 },
      );
    }

    return NextResponse.json({
      waitlist: {
        id: waitlist.id,
        title: waitlist.title,
        titleAr: waitlist.titleAr,
        description: waitlist.description,
        descriptionAr: waitlist.descriptionAr,
        category: waitlist.category,
        isActive: waitlist.isActive,
        createdBy: waitlist.createdBy,
        createdAt: waitlist.createdAt,
        updatedAt: waitlist.updatedAt,
        signupCount: waitlist._count.signups,
        signups: waitlist.signups,
      },
    });
  } catch (error) {
    console.error("Failed to fetch waitlist:", error);
    return NextResponse.json(
      { error: "Failed to fetch waitlist" },
      { status: 500 },
    );
  }
}

/**
 * PATCH /api/staff/dashboard/waitlists/[id]
 * Update a waitlist
 */
export async function PATCH(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = params;
    const body = await request.json();
    const { title, titleAr, description, descriptionAr, category, isActive } =
      body;

    // Check waitlist exists
    const existing = await prisma.waitlists.findUnique({
      where: { id },
    });

    if (!existing) {
      return NextResponse.json(
        { error: "Waitlist not found" },
        { status: 404 },
      );
    }

    // Validate category if provided
    const validCategories = [
      "product",
      "feature",
      "service",
      "event",
      "help",
      "general",
    ];

    // Build update data
    const updateData: Record<string, unknown> = {};
    if (title !== undefined) updateData.title = title.trim();
    if (titleAr !== undefined) updateData.titleAr = titleAr?.trim() || null;
    if (description !== undefined)
      updateData.description = description?.trim() || null;
    if (descriptionAr !== undefined)
      updateData.descriptionAr = descriptionAr?.trim() || null;
    if (category !== undefined && validCategories.includes(category))
      updateData.category = category;
    if (isActive !== undefined) updateData.isActive = isActive;

    const waitlist = await prisma.waitlists.update({
      where: { id },
      data: updateData,
    });

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

/**
 * DELETE /api/staff/dashboard/waitlists/[id]
 * Delete a waitlist
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = params;

    // Check waitlist exists
    const existing = await prisma.waitlists.findUnique({
      where: { id },
    });

    if (!existing) {
      return NextResponse.json(
        { error: "Waitlist not found" },
        { status: 404 },
      );
    }

    // Delete waitlist (cascade will delete signups)
    await prisma.waitlists.delete({
      where: { id },
    });

    return NextResponse.json({
      success: true,
      message: "Waitlist deleted successfully",
    });
  } catch (error) {
    console.error("Failed to delete waitlist:", error);
    return NextResponse.json(
      { error: "Failed to delete waitlist" },
      { status: 500 },
    );
  }
}
