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

// 1x1 transparent GIF (optimal format for pixels)
const TRANSPARENT_GIF_BASE64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
const TRANSPARENT_GIF = Uint8Array.from(atob(TRANSPARENT_GIF_BASE64), c => c.charCodeAt(0));

serve(async (req) => {
  try {
    const url = new URL(req.url);
    const id = url.searchParams.get("id");

    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 open event in our isolated table
      const { error } = await supabaseClient
        .from("email_opens")
        .insert({
           email_send_id: id,
           ip_address: req.headers.get("x-forwarded-for") ?? "unknown",
           user_agent: req.headers.get("user-agent") ?? "unknown"
        });

      if (error) {
        console.error("Error inserting email open event:", error);
      }
    }
  } catch (error) {
    console.error("Tracking open exception:", error);
  }

  // Always immediately return the tracking pixel
  return new Response(TRANSPARENT_GIF, {
    status: 200,
    headers: {
      "Content-Type": "image/gif",
      // Crucial explicit caching headers to ensure multiple opens are tracked uniquely
      "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
      "Pragma": "no-cache",
      "Expires": "0",
    },
  });
});
