import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.49.1";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, svix-id, svix-timestamp, svix-signature",
};

serve(async (req: Request): Promise<Response> => {
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabase = createClient(supabaseUrl, supabaseServiceKey);

    const payload = await req.json();
    console.log("Resend webhook received:", JSON.stringify(payload));

    const { type, data } = payload;

    switch (type) {
      case "email.bounced": {
        const email = data.to?.[0] || data.email;
        if (email) {
          // Add to suppression list
          await supabase.from("suppression_list").upsert({
            email: email,
            reason: "bounce",
          }, { onConflict: "email" });

          // Update email log
          if (data.email_id) {
            await supabase
              .from("email_logs")
              .update({ status: "bounced" })
              .eq("resend_id", data.email_id);
          }

          console.log(`Bounce recorded for: ${email}`);
        }
        break;
      }

      case "email.complained": {
        const email = data.to?.[0] || data.email;
        if (email) {
          // Add to suppression list
          await supabase.from("suppression_list").upsert({
            email: email,
            reason: "complaint",
          }, { onConflict: "email" });

          // Update email log
          if (data.email_id) {
            await supabase
              .from("email_logs")
              .update({ status: "complained" })
              .eq("resend_id", data.email_id);
          }

          console.log(`Complaint recorded for: ${email}`);
        }
        break;
      }

      case "email.delivered": {
        console.log(`Email delivered: ${data.email_id}`);
        break;
      }

      case "email.opened": {
        console.log(`Email opened: ${data.email_id}`);
        break;
      }

      case "email.clicked": {
        console.log(`Email clicked: ${data.email_id}`);
        break;
      }

      default:
        console.log(`Unhandled webhook type: ${type}`);
    }

    return new Response(
      JSON.stringify({ received: true }),
      { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );

  } catch (error: any) {
    console.error("Webhook error:", error);
    return new Response(
      JSON.stringify({ error: error.message }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
