import type { APIRoute } from 'astro';

const DIRECTUS_URL =
  import.meta.env.DIRECTUS_URL ||
  process.env.DIRECTUS_URL ||
  'http://localhost:8055';

const DIRECTUS_TOKEN =
  import.meta.env.DIRECTUS_TOKEN ||
  process.env.DIRECTUS_TOKEN ||
  '';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ALLOWED_SHOOT = new Set(['mariage', 'portrait-lifestyle', 'reportage-editorial', 'evenementiel', 'autre', '']);

type Payload = {
  name?: string;
  email?: string;
  shoot_type?: string;
  date_estim?: string;
  lieu?: string;
  budget?: string;
  message?: string;
  website?: string;
};

function clean(v: unknown, max: number): string {
  if (typeof v !== 'string') return '';
  return v.trim().slice(0, max);
}

function jsonResponse(body: unknown, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

export const POST: APIRoute = async ({ request, clientAddress }) => {
  let p: Payload;
  try {
    p = (await request.json()) as Payload;
  } catch {
    return jsonResponse({ ok: false, error: 'INVALID_JSON' }, 400);
  }

  // Honeypot : si rempli, c'est un bot → on retourne 200 OK silencieux
  // pour ne pas le notifier que la protection a déclenché.
  if (clean(p.website, 200) !== '') {
    return jsonResponse({ ok: true, id: null });
  }

  const name = clean(p.name, 120);
  const email = clean(p.email, 200).toLowerCase();
  const shoot_type = clean(p.shoot_type, 40);
  const date_estim = clean(p.date_estim, 120);
  const lieu = clean(p.lieu, 200);
  const budget = clean(p.budget, 120);
  const message = clean(p.message, 4000);

  if (!name || !email || !message) {
    return jsonResponse({ ok: false, error: 'MISSING_REQUIRED', fields: ['name', 'email', 'message'].filter((f) => !({ name, email, message } as Record<string, string>)[f]) }, 400);
  }
  if (!EMAIL_RE.test(email)) {
    return jsonResponse({ ok: false, error: 'INVALID_EMAIL' }, 400);
  }
  if (!ALLOWED_SHOOT.has(shoot_type)) {
    return jsonResponse({ ok: false, error: 'INVALID_SHOOT_TYPE' }, 400);
  }

  const ua = clean(request.headers.get('user-agent') || '', 500);
  const ip = clean(
    request.headers.get('x-forwarded-for')?.split(',')[0] || clientAddress || '',
    64
  );

  const body = {
    name,
    email,
    shoot_type: shoot_type || null,
    date_estim: date_estim || null,
    lieu: lieu || null,
    budget: budget || null,
    message,
    ip_address: ip || null,
    user_agent: ua || null,
  };

  const res = await fetch(`${DIRECTUS_URL}/items/contact_requests`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${DIRECTUS_TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!res.ok) {
    const text = await res.text();
    console.error('[contact] directus error', res.status, text.slice(0, 300));
    return jsonResponse({ ok: false, error: 'STORAGE_FAILED' }, 502);
  }

  const data = (await res.json()) as { data?: { id: number } };
  // TODO: déclencher la notification email ici (Resend / Nodemailer / Directus Flow webhook)
  return jsonResponse({ ok: true, id: data.data?.id ?? null });
};
