import { z } from 'zod';

const schema = z.object({
  name: z.string().min(1).max(120),
  email: z.string().email(),
  phone: z.string().max(30).optional(),
  location: z.array(z.string().min(1).max(80)).min(1).max(51),
  interests: z.array(z.enum(['entertainment', 'clothing', 'home', 'experiences', 'workshops', 'restaurants'])),
  locale: z.enum(['he', 'en']),
});

export default async (request: Request): Promise<Response> => {
  // Only accept POST
  if (request.method !== 'POST') {
    return new Response('Method Not Allowed', { status: 405 });
  }

  // Parse body
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return new Response(JSON.stringify({ error: 'Invalid JSON' }), { status: 400 });
  }

  // Validate
  const parsed = schema.safeParse(body);
  if (!parsed.success) {
    return new Response(JSON.stringify({ error: 'Invalid input', issues: parsed.error.issues }), { status: 400 });
  }

  const { name, email, phone, location, interests, locale } = parsed.data;

  // Get secrets from environment (Pages Functions env variables)
  const apiKey = process.env.BREVO_API_KEY;
  const listIdRaw = process.env.BREVO_LIST_ID;

  if (!apiKey || !listIdRaw) {
    return new Response(JSON.stringify({ ok: true, skipped: true }), { status: 200 });
  }

  const listId = parseInt(listIdRaw, 10);
  if (isNaN(listId)) {
    return new Response(JSON.stringify({ error: 'BREVO_LIST_ID must be a number' }), { status: 500 });
  }

  // Split name into first/last
  const parts = name.trim().split(/\s+/);
  const firstName = parts[0];
  const lastName = parts.slice(1).join(' ') || '';

  // POST to Brevo
  try {
    const brevoRes = await fetch('https://api.brevo.com/v3/contacts', {
      method: 'POST',
      headers: {
        'api-key': apiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        attributes: {
          FIRSTNAME: firstName,
          LASTNAME: lastName,
          ...(phone ? { SMS: phone } : {}),
          LOCATION: location.join(','),
          INTERESTS: interests.join(','),
          LOCALE: locale,
        },
        listIds: [listId],
        updateEnabled: true,
      }),
    });

    if (!brevoRes.ok && brevoRes.status !== 204) {
      console.error('[subscribe] Brevo error', brevoRes.status);
      return new Response(JSON.stringify({ error: 'Subscription service error' }), { status: 500 });
    }

    return new Response(JSON.stringify({ ok: true }), { status: 200 });
  } catch (error) {
    console.error('[subscribe] Error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });
  }
};
