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

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

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

/**
 * GET /api/waitlists/[id]
 * Get a single waitlist with its signups (only for owner)
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  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 { id } = params;
    const userId = authenticatedUser.userId;

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

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

    // Check ownership
    if (waitlist.userId !== userId) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    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,
        isPublic: waitlist.isPublic,
        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/waitlists/[id]
 * Update a waitlist (only owner can update)
 */
export async function PATCH(request: NextRequest, { params }: RouteParams) {
  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 { id } = params;
    const userId = authenticatedUser.userId;
    const body = await request.json();
    const {
      title,
      titleAr,
      description,
      descriptionAr,
      category,
      isActive,
      isPublic,
    } = body;

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

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

    if (existing.userId !== userId) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    // Build update data
    const updateData: any = {};
    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 && VALID_CATEGORIES.includes(category))
      updateData.category = category;
    if (isActive !== undefined) updateData.isActive = isActive;
    if (isPublic !== undefined) updateData.isPublic = isPublic;

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

    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,
        updatedAt: waitlist.updatedAt,
      },
    });
  } catch (error) {
    console.error("Failed to update waitlist:", error);
    return NextResponse.json(
      { error: "Failed to update waitlist" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/waitlists/[id]
 * Delete a waitlist (only owner can delete)
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  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 { id } = params;
    const userId = authenticatedUser.userId;

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

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

    if (existing.userId !== userId) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    // 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 },
    );
  }
}
