import { NextRequest, NextResponse } from "next/server";

interface DemoRequest {
  name: string;
  business: string;
  phone: string;
  email?: string;
  branches: string;
  message?: string;
}

export async function POST(req: NextRequest) {
  try {
    const body = (await req.json()) as DemoRequest;

    // Validate required fields
    if (!body.name?.trim() || !body.business?.trim() || !body.phone?.trim()) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 }
      );
    }

    // Basic phone validation (Iranian format)
    const phoneClean = body.phone.replace(/\s|-/g, "");
    if (phoneClean.length < 10) {
      return NextResponse.json(
        { success: false, error: "Invalid phone number" },
        { status: 400 }
      );
    }

    // In production: send email via SMTP / save to DB / forward to CRM
    // For now: forward to Meezi API
    const apiBase = process.env.MEEZI_API_URL ?? "https://api.meezi.ir";
    try {
      await fetch(`${apiBase}/api/public/demo-requests`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contactName: body.name.trim(),
          businessName: body.business.trim(),
          phone: phoneClean,
          email: body.email?.trim() || null,
          branchCount: body.branches,
          notes: body.message?.trim() || null,
          source: "website",
        }),
      });
    } catch {
      // Don't fail the request if backend is unreachable — log and continue
      console.error("[demo] Failed to forward to API");
    }

    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 }
    );
  }
}
