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 {
  // Remove spaces, dashes, parentheses
  const cleaned = mobile.replace(/[\s\-\(\)]/g, "");
  // Should be at least 8 digits, optionally starting with +
  return /^\+?\d{8,15}$/.test(cleaned);
}

/**
 * POST /api/waitlists/[id]/signup
 * Sign up for a waitlist
 */
export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const { id: waitlistId } = params;
    const body = await request.json();
    const { name, email, mobile } = body;

    // 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 waitlist exists and is active
    const waitlist = await prisma.waitlists.findUnique({
      where: { id: waitlistId },
    });

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

    if (!waitlist.isActive) {
      return NextResponse.json(
        { error: "This waitlist is no longer accepting signups" },
        { status: 400 },
      );
    }

    // Get session (optional) - supports both NextAuth and OTP auth_token
    const authenticatedUser = await getAuthenticatedUser(request, auth);
    const userId = authenticatedUser?.userId || null;

    // 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: "You have already signed up for this waitlist" },
        { status: 409 },
      );
    }

    // Create signup
    const id = createId();
    const signup = await prisma.waitlist_signups.create({
      data: {
        id,
        waitlistId,
        userId,
        name: name.trim(),
        email: email.trim().toLowerCase(),
        mobile: mobile.trim(),
      },
    });

    return NextResponse.json({
      success: true,
      message: "Successfully signed up for waitlist",
      signup: {
        id: signup.id,
        name: signup.name,
        email: signup.email,
        createdAt: signup.createdAt,
      },
    });
  } catch (error: any) {
    console.error("Failed to sign up for waitlist:", error);

    // Handle unique constraint violation
    if (error?.code === "P2002") {
      return NextResponse.json(
        { error: "You have already signed up for this waitlist" },
        { status: 409 },
      );
    }

    return NextResponse.json(
      { error: "Failed to sign up for waitlist" },
      { status: 500 },
    );
  }
}
