// Public endpoint for avriacam.com contact form submissions.
// Inserts into form_inbox with source_type = 'avriacam_contact'.
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
};

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });

  try {
    const body = await req.json().catch(() => ({}));
    const name = String(body.name ?? body.full_name ?? "").trim();
    const email = String(body.email ?? "").trim();
    const subject = String(body.subject ?? body.topic ?? "Contact Form Submission").trim();
    const message = String(body.message ?? body.body ?? "").trim();
    const phone = body.phone ? String(body.phone).trim() : "";
    const company = body.company ? String(body.company).trim() : "";

    if (!email || !message) {
      return new Response(JSON.stringify({ error: "email and message are required" }), {
        status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
    );

    // Source id is synthetic (no underlying record). Use a uuid.
    const sourceId = crypto.randomUUID();

    const summaryParts = [
      phone ? `Phone: ${phone}` : null,
      company ? `Company: ${company}` : null,
      message,
    ].filter(Boolean);

    const { data, error } = await supabase
      .from("form_inbox")
      .insert({
        source_type: "avriacam_contact",
        source_id: sourceId,
        association_id: null,
        title: `[avriacam.com] ${subject}`,
        submitter_name: name || null,
        submitter_email: email,
        summary: summaryParts.join(" | ").slice(0, 1000),
      })
      .select("id")
      .single();

    if (error) throw error;

    return new Response(JSON.stringify({ ok: true, id: data.id }), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (e) {
    return new Response(JSON.stringify({ error: (e as Error).message }), {
      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
