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

// A 1x1 transparent PNG base64 encoded
const TRANSPARENT_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
const TRANSPARENT_PNG = Uint8Array.from(atob(TRANSPARENT_PNG_BASE64), c => c.charCodeAt(0));

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

    if (id) {
      // Connect to supabase
      const supabaseClient = createClient(
        Deno.env.get("SUPABASE_URL") ?? "",
        Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? Deno.env.get("SUPABASE_ANON_KEY") ?? ""
      );

      // Verify id is valid UUID pattern
      if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
        // Fetch current opens
        const { data, error } = await supabaseClient
          .from("sent_history")
          .select("opens")
          .eq("id", id)
          .single();

        if (data && !error) {
          await supabaseClient
            .from("sent_history")
            .update({ 
               opens: (data.opens || 0) + 1,
               last_opened_at: new Date().toISOString()
            })
            .eq("id", id);
        }
      }
    }
  } catch (error) {
    console.error("Error tracking open:", error);
  }

  // Always return the PNG
  return new Response(TRANSPARENT_PNG, {
    headers: {
      "Content-Type": "image/png",
      "Cache-Control": "no-store",
    },
    status: 200,
  });
});
