import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.39.0"
import nodemailer from "npm:nodemailer"

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

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

  try {
    // Initialize Supabase Client with Service Role to bypass RLS for background jobs
    const supabaseUrl = Deno.env.get('SUPABASE_URL') || '';
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') || Deno.env.get('SUPABASE_ANON_KEY') || '';
    
    if (!supabaseUrl || !supabaseKey) {
      throw new Error("Missing Supabase environment variables");
    }

    const supabase = createClient(supabaseUrl, supabaseKey);

    // 1. Fetch pending scheduled campaigns that are due
    const { data: campaigns, error: fetchError } = await supabase
      .from('scheduled_campaigns')
      .select('*, templates(*)')
      .eq('status', 'pending')
      .lte('scheduled_at', new Date().toISOString())
      .limit(5);

    if (fetchError) throw fetchError;
    if (!campaigns || campaigns.length === 0) {
      return new Response(JSON.stringify({ message: "No pending campaigns due." }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' } })
    }

    const transporter = nodemailer.createTransport({
      host: "mail.privateemail.com",
      port: 465,
      secure: true, 
      pool: true,
      auth: {
        user: "info@baytownnetworkingprofessionals.com",
        pass: "C^S3v%WC0Vdi",
      },
      connectionTimeout: 10000,
    })

    // Process each campaign
    for (const campaign of campaigns) {
      // Mark as processing
      await supabase.from('scheduled_campaigns').update({ status: 'processing' }).eq('id', campaign.id);

      try {
        let emailsToSend = [];
        
        if (campaign.sending_mode === 'test' && campaign.test_email) {
          emailsToSend.push({ email: campaign.test_email });
        } else {
          // Fetch contacts
          const { data: contacts, error: contactError } = await supabase
            .from(campaign.target_table)
            .select('*')
            .range(campaign.start_row - 1, campaign.start_row - 1 + campaign.batch_count - 1);
          
          if (contactError) throw contactError;
          if (contacts) emailsToSend = contacts;
        }

        // Dispatch emails
        for (const contact of emailsToSend) {
          if (!contact.email) continue;
          
          await transporter.sendMail({
            from: '"Sunbelt Metrics" <info@baytownnetworkingprofessionals.com>',
            to: contact.email,
            subject: campaign.templates?.subject_line || 'Sunbelt Metrics Notification',
            html: campaign.templates?.content_body || 'Empty message content.',
          });
          
          // Small delay to prevent rate limits
          await new Promise(r => setTimeout(r, 200));
        }

        // Mark as completed
        await supabase.from('scheduled_campaigns').update({ status: 'completed' }).eq('id', campaign.id);
        
      } catch (err: any) {
        console.error(`Failed campaign ${campaign.id}:`, err);
        await supabase.from('scheduled_campaigns').update({ status: 'failed' }).eq('id', campaign.id);
      }
    }

    return new Response(
      JSON.stringify({ success: true, processed: campaigns.length }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
    )

  } catch (error: any) {
    console.error("Error in scheduler function:", error.message)
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 500 }
    )
  }
})
