import { NextRequest, NextResponse } from "next/server";
import { sendBrochureSalesNotification } from "@/lib/brochureMailer";
import {
  createBrochureRequest,
  fetchLatestBrochureRequest,
  fetchPropertyContextForBrochureLead,
  updateBrochureRequest,
} from "@/utils/strapi";

const USER_SUCCESS_MESSAGE =
  "Your request has been sent. Our sales team will email you the brochure — please wait a few minutes.";

const successJson = () =>
  NextResponse.json({ message: USER_SUCCESS_MESSAGE }, { status: 200 });

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const email = String(body?.email || "").trim();
    const phone = String(body?.phone || "").trim();
    const propertyKey = String(body?.propertyKey || "unknown-property").trim();

    if (!email || !phone) {
      return NextResponse.json(
        { message: "Email and phone are required." },
        { status: 400 }
      );
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return NextResponse.json(
        { message: "Please provide a valid email address." },
        { status: 400 }
      );
    }

    // Permanent dedupe: same email + phone already submitted before → silently
    // succeed without creating a new row or re-notifying sales.
    const existingRequest = await fetchLatestBrochureRequest({
      email: email.toLowerCase(),
      phone,
    });

    if (existingRequest) {
      return successJson();
    }

    const propertyCtx = await fetchPropertyContextForBrochureLead(propertyKey);
    const propertyName = propertyCtx?.propertyName?.trim() || propertyKey;
    const propertyAddress =
      propertyCtx?.propertyAddress?.trim() || "Not specified";
    const propertyType = propertyCtx?.propertyType ?? null;

    const record = await createBrochureRequest({
      email: email.toLowerCase(),
      phone,
      propertyName,
      propertyAddress,
      propertyType,
    });

    if (!record?.id) {
      console.error(
        "download-brochure: brochure-requests create returned no id (Strapi config / validation)."
      );
      return successJson();
    }

    try {
      await sendBrochureSalesNotification({
        customerEmail: email.toLowerCase(),
        phone,
        propertyKey,
        propertyName,
        propertyAddress,
        propertyType,
      });
      await updateBrochureRequest(record.id, {
        mailSentAt: new Date().toISOString(),
      });
    } catch (mailError) {
      console.error("download-brochure: sales mail failed:", mailError);
    }

    return successJson();
  } catch (error) {
    console.error("download-brochure API error:", error);
    return successJson();
  }
}
