/**
 * Cloudflare Worker: MCPEngage Waitlist → GoHighLevel proxy
 * Hides the API key server-side. Deploy to: waitlist.mcpengage.com or similar
 */
export default {
  async fetch(request, env) {
    // CORS preflight
    if (request.method === 'OPTIONS') {
      return new Response(null, {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type',
          'Access-Control-Max-Age': '86400',
        },
      });
    }

    if (request.method !== 'POST') {
      return new Response(JSON.stringify({ error: 'POST only' }), { status: 405, headers: { 'Content-Type': 'application/json' } });
    }

    try {
      const body = await request.json();

      // Validate required fields
      if (!body.firstName || !body.lastName || !body.phone) {
        return new Response(JSON.stringify({ error: 'firstName, lastName, and phone are required' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
        });
      }

      // Build GHL contact payload
      const ghlPayload = {
        firstName: body.firstName,
        lastName: body.lastName,
        name: body.firstName + ' ' + body.lastName,
        phone: body.phone,
        tags: body.tags || ['MCP waitlist'],
        source: body.source || 'MCPEngage Waitlist',
        locationId: env.GHL_LOCATION_ID || 'DZEpRd43MxUJKdtrev9t',
      };
      if (body.email) ghlPayload.email = body.email;

      const ghlRes = await fetch('https://services.leadconnectorhq.com/contacts/', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer ' + (env.GHL_API_KEY || ''),
          'Content-Type': 'application/json',
          'Version': '2021-07-28',
        },
        body: JSON.stringify(ghlPayload),
      });

      const ghlData = await ghlRes.json();

      return new Response(JSON.stringify({ ok: ghlRes.ok, contact: ghlData.contact?.id || null }), {
        status: ghlRes.ok ? 200 : 500,
        headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
      });
    } catch (err) {
      return new Response(JSON.stringify({ error: err.message }), {
        status: 500,
        headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
      });
    }
  },
};
