import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

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

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

  try {
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    const supabase = createClient(
      Deno.env.get('SUPABASE_URL')!,
      Deno.env.get('SUPABASE_ANON_KEY')!,
      { global: { headers: { Authorization: authHeader } } }
    );

    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    const body = await req.json();
    const { action, api_key, server_prefix, audience_name, association_name, from_name, from_email } = body;

    if (!api_key || !server_prefix) {
      return new Response(JSON.stringify({ error: 'Missing api_key or server_prefix' }), {
        status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    const baseUrl = `https://${server_prefix}.api.mailchimp.com/3.0`;
    const authHeaderMc = `Basic ${btoa(`anystring:${api_key}`)}`;

    if (action === 'ping') {
      const r = await fetch(`${baseUrl}/ping`, { headers: { Authorization: authHeaderMc } });
      const data = await r.json();
      if (!r.ok) {
        return new Response(JSON.stringify({ success: false, error: data.detail || 'Ping failed' }), {
          status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        });
      }
      return new Response(JSON.stringify({ success: true, data }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    if (action === 'list') {
      const r = await fetch(`${baseUrl}/lists?count=100`, { headers: { Authorization: authHeaderMc } });
      const data = await r.json();
      if (!r.ok) {
        return new Response(JSON.stringify({ success: false, error: data.detail || 'List failed' }), {
          status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        });
      }
      return new Response(JSON.stringify({ success: true, lists: data.lists || [] }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    if (action === 'create') {
      const payload = {
        name: audience_name || association_name || 'HOA Owners',
        contact: {
          company: association_name || 'HOA',
          address1: 'N/A',
          city: 'N/A',
          state: 'N/A',
          zip: '00000',
          country: 'US',
        },
        permission_reminder: 'You are receiving this because you are an owner in this association.',
        campaign_defaults: {
          from_name: from_name || association_name || 'HOA',
          from_email: from_email || user.email || 'noreply@example.com',
          subject: '',
          language: 'en',
        },
        email_type_option: false,
      };

      const r = await fetch(`${baseUrl}/lists`, {
        method: 'POST',
        headers: { Authorization: authHeaderMc, 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await r.json();
      if (!r.ok) {
        return new Response(JSON.stringify({ success: false, error: data.detail || data.title || 'Create failed' }), {
          status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        });
      }
      return new Response(JSON.stringify({ success: true, list: data }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      });
    }

    return new Response(JSON.stringify({ error: 'Unknown action' }), {
      status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), {
      status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
});
