import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import validator from "validator";
import DOMPurify from "isomorphic-dompurify";
import { logger } from "@/lib/logger";
import { convexMutation } from "@/lib/convex-client";
import { getDataSource } from "@/lib/data-source";
import { prisma } from "@/lib/db";
import { validateCSRFToken } from "@/lib/csrf";

// Validation schema
const contactSchema = z.object({
  name: z.string().min(2).max(100),
  email: z.string().email(),
  phone: z.string().optional(),
  company: z.string().optional(),
  message: z.string().min(10).max(2000),
  language: z.enum(["ar", "en"]).default("ar"),
});

export async function POST(request: NextRequest) {
  // CSRF validation (bypass in development for testing)
  if (process.env.NODE_ENV === "production") {
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { error: "Invalid or missing CSRF token" },
        { status: 403 },
      );
    }
  }

  try {
    const body = await request.json();

    // Validate input
    const validation = contactSchema.safeParse(body);
    if (!validation.success) {
      return NextResponse.json(
        { error: "Invalid input", details: validation.error.errors },
        { status: 400 },
      );
    }

    const { name, email, phone, company, message, language } = validation.data;

    // Additional validation
    if (!validator.isEmail(email)) {
      return NextResponse.json(
        { error: "Invalid email address" },
        { status: 400 },
      );
    }

    // Sanitize inputs
    const sanitizedData = {
      name: DOMPurify.sanitize(name),
      email: validator.normalizeEmail(email) || email,
      phone: phone ? DOMPurify.sanitize(phone) : null,
      company: company ? DOMPurify.sanitize(company) : null,
      message: DOMPurify.sanitize(message),
      language,
    };

    // Extract request metadata
    const ipAddress =
      request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
      request.headers.get("x-real-ip") ??
      "unknown";
    const userAgent = request.headers.get("user-agent") ?? "unknown";

    // Save contact submission
    let contact: { id: string };
    if (getDataSource("support") === "convex") {
      const convexId = await convexMutation(
        "support/mutations:createContactSubmission",
        {
          name: sanitizedData.name,
          email: sanitizedData.email,
          phone: sanitizedData.phone,
          company: sanitizedData.company ?? undefined,
          message: sanitizedData.message,
          language: sanitizedData.language,
          ip_address: ipAddress,
          user_agent: userAgent,
        },
      );
      contact = { id: convexId as string };
    } else {
      // Save to Prisma
      const saved = await prisma.contact_submissions.create({
        data: {
          name: sanitizedData.name,
          email: sanitizedData.email,
          phone: sanitizedData.phone ?? "",
          company: sanitizedData.company ?? null,
          message: sanitizedData.message,
          language: sanitizedData.language,
          ipAddress,
          userAgent,
          status: "new",
        },
      });
      contact = { id: saved.id };
    }

    // Create staff alert for new contact (Convex)
    await convexMutation("notifications/mutations:createStaffAlert", {
      type: "NEW_CONTACT",
      title: "New Contact Form Submission",
      message: `${sanitizedData.name} submitted a contact form`,
      severity: "INFO",
      metadata: {
        contactId: contact.id,
        email: sanitizedData.email,
        name: sanitizedData.name,
      },
    });

    // TODO: Send email notification to staff
    // await sendStaffNotification('NEW_CONTACT', contact);

    return NextResponse.json({
      success: true,
      message: "Contact form submitted successfully",
      contactId: contact.id,
    });
  } catch (error) {
    console.error("Contact form error:", error);
    return NextResponse.json(
      { error: "Failed to submit contact form" },
      { status: 500 },
    );
  }
}
