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

serve(async (req) => {
  try {
    const url = new URL(req.url);
    const id = url.searchParams.get("id");
    
    // Using simple gets for URL. We're assuming it was encoded via encodeURIComponent.
    const destinationUrl = url.searchParams.get("url");

    if (!destinationUrl) {
      return new Response("Missing destination URL", { status: 400 });
    }

    if (id && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
      const supabaseUrl = Deno.env.get("SUPABASE_URL") ?? "";
      const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? Deno.env.get("SUPABASE_ANON_KEY") ?? "";
      
      const supabaseClient = createClient(supabaseUrl, supabaseKey);

      // Record the click event in our isolated table
      const { error } = await supabaseClient
        .from("email_clicks")
        .insert({
           email_send_id: id,
           url: destinationUrl,
           ip_address: req.headers.get("x-forwarded-for") ?? "unknown",
           user_agent: req.headers.get("user-agent") ?? "unknown"
        });

      if (error) {
        console.error("Error inserting email click event:", error);
      }
    }

    // Always immediately redirect the user to prevent noticeable delay
    return new Response(null, {
      status: 302,
      headers: {
        Location: destinationUrl,
        "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
        "Pragma": "no-cache",
        "Expires": "0"
      },
    });

  } catch (error) {
    console.error("Tracking click exception:", error);
    
    // Fallback: Even if something totally fails, attempt to redirect if we have a target
    try {
      const url = new URL(req.url);
      const dest = url.searchParams.get("url");
      if (dest) {
        return new Response(null, { status: 302, headers: { Location: dest } });
      }
    } catch (_) {
      // ignore nested fail
    }

    return new Response("Internal Server Error", { status: 500 });
  }
});
