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";

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

// Simple email validation
function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// Simple mobile validation (allows various formats)
function isValidMobile(mobile: string): boolean {
  const cleaned = mobile.replace(/[\s\-\(\)]/g, "");
  return /^\+?\d{8,15}$/.test(cleaned);
}

/**
 * GET /api/waitlists/[id]/signups
 * List signups for a waitlist (only owner can view)
 */
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: waitlistId } = params;
    const userId = authenticatedUser.userId;
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "50");
    const search = searchParams.get("search");

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

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

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

    // Build where clause
    const where: any = { waitlistId };
    if (search) {
      where.OR = [
        { name: { contains: search, mode: "insensitive" } },
        { email: { contains: search, mode: "insensitive" } },
        { mobile: { contains: search, mode: "insensitive" } },
      ];
    }

    const skip = (page - 1) * limit;

    const [signups, totalCount] = await Promise.all([
      prisma.waitlist_signups.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
      }),
      prisma.waitlist_signups.count({ where }),
    ]);

    return NextResponse.json({
      signups,
      pagination: {
        page,
        limit,
        total: totalCount,
        totalPages: Math.ceil(totalCount / limit),
        hasMore: skip + signups.length < totalCount,
      },
    });
  } catch (error) {
    console.error("Failed to fetch waitlist signups:", error);
    return NextResponse.json(
      { error: "Failed to fetch signups" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/waitlists/[id]/signups
 * Add a user to a waitlist (owner can add users manually)
 */
export async function POST(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: waitlistId } = params;
    const userId = authenticatedUser.userId;
    const body = await request.json();
    const { name, email, mobile, notes } = body;

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

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

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

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

    if (!email || typeof email !== "string" || !isValidEmail(email.trim())) {
      return NextResponse.json(
        { error: "Valid email is required" },
        { status: 400 },
      );
    }

    if (
      !mobile ||
      typeof mobile !== "string" ||
      !isValidMobile(mobile.trim())
    ) {
      return NextResponse.json(
        { error: "Valid mobile number is required" },
        { status: 400 },
      );
    }

    // Check for duplicate signup (by email)
    const existingSignup = await prisma.waitlist_signups.findUnique({
      where: {
        waitlistId_email: {
          waitlistId,
          email: email.trim().toLowerCase(),
        },
      },
    });

    if (existingSignup) {
      return NextResponse.json(
        { error: "This email is already signed up for this waitlist" },
        { status: 409 },
      );
    }

    // Create signup
    const id = createId();
    const signup = await prisma.waitlist_signups.create({
      data: {
        id,
        waitlistId,
        userId: null, // Manually added, no linked user account
        name: name.trim(),
        email: email.trim().toLowerCase(),
        mobile: mobile.trim(),
        notes: notes?.trim() || null,
        addedBy: userId,
      },
    });

    return NextResponse.json({
      success: true,
      message: "User added to waitlist successfully",
      signup: {
        id: signup.id,
        name: signup.name,
        email: signup.email,
        mobile: signup.mobile,
        notes: signup.notes,
        createdAt: signup.createdAt,
      },
    });
  } catch (error) {
    console.error("Failed to add user to waitlist:", error);
    return NextResponse.json(
      { error: "Failed to add user to waitlist" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/waitlists/[id]/signups?signupId=xxx
 * Remove a signup from a waitlist (owner can remove)
 */
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: waitlistId } = params;
    const userId = authenticatedUser.userId;
    const { searchParams } = new URL(request.url);
    const signupId = searchParams.get("signupId");

    if (!signupId) {
      return NextResponse.json(
        { error: "signupId is required" },
        { status: 400 },
      );
    }

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

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

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

    // Check signup exists and belongs to this waitlist
    const signup = await prisma.waitlist_signups.findFirst({
      where: { id: signupId, waitlistId },
    });

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

    // Delete signup
    await prisma.waitlist_signups.delete({
      where: { id: signupId },
    });

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