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";

serve(async (req: Request): Promise<Response> => {
  try {
    const url = new URL(req.url);
    const email = url.searchParams.get("email");
    const campaignId = url.searchParams.get("campaign_id");

    if (!email) {
      return new Response(
        `<!DOCTYPE html>
        <html>
        <head><title>Error</title></head>
        <body style="font-family: Arial, sans-serif; text-align: center; padding: 50px;">
          <h1>Invalid Request</h1>
          <p>Email address is required.</p>
        </body>
        </html>`,
        { status: 400, headers: { "Content-Type": "text/html" } }
      );
    }

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

    // Check if already unsubscribed
    const { data: existing } = await supabase
      .from("suppression_list")
      .select("id")
      .eq("email", email)
      .maybeSingle();

    if (!existing) {
      // Add to suppression list
      await supabase.from("suppression_list").insert({
        email: email,
        reason: "unsubscribe",
        source_campaign_id: campaignId || null,
      });

      console.log(`Unsubscribed: ${email}`);
    }

    // Return confirmation page
    return new Response(
      `<!DOCTYPE html>
      <html>
      <head>
        <title>Unsubscribed</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
          body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
          }
          .card {
            background: white;
            border-radius: 16px;
            padding: 40px;
            max-width: 400px;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
          }
          .icon {
            font-size: 64px;
            margin-bottom: 20px;
          }
          h1 {
            color: #333;
            margin: 0 0 16px;
            font-size: 24px;
          }
          p {
            color: #666;
            margin: 0;
            line-height: 1.6;
          }
        </style>
      </head>
      <body>
        <div class="card">
          <div class="icon">✓</div>
          <h1>Successfully Unsubscribed</h1>
          <p>You have been removed from our mailing list and will no longer receive marketing emails from us.</p>
        </div>
      </body>
      </html>`,
      { status: 200, headers: { "Content-Type": "text/html" } }
    );

  } catch (error: any) {
    console.error("Unsubscribe error:", error);
    return new Response(
      `<!DOCTYPE html>
      <html>
      <head><title>Error</title></head>
      <body style="font-family: Arial, sans-serif; text-align: center; padding: 50px;">
        <h1>Something went wrong</h1>
        <p>Please try again later or contact support.</p>
      </body>
      </html>`,
      { status: 500, headers: { "Content-Type": "text/html" } }
    );
  }
});
