import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

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

const pixel = Uint8Array.from([
  71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 255, 255, 255, 0, 0, 0,
  33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59,
]);

function pixelResponse(status = 200) {
  return new Response(pixel, {
    status,
    headers: {
      ...corsHeaders,
      "Content-Type": "image/gif",
      "Content-Length": String(pixel.length),
      "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",
      "Pragma": "no-cache",
      "Expires": "0",
    },
  });
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
  if (req.method !== "GET" && req.method !== "HEAD") return pixelResponse(405);

  try {
    const trackingId = new URL(req.url).searchParams.get("tid")?.trim();
    if (!trackingId || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trackingId)) {
      return pixelResponse(200);
    }

    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabase = createClient(supabaseUrl, serviceKey, {
      auth: { autoRefreshToken: false, persistSession: false },
    });

    const { data: row, error: selectError } = await supabase
      .from("email_history")
      .select("id, open_count")
      .eq("tracking_id", trackingId)
      .maybeSingle();

    if (!selectError && row?.id) {
      await supabase
        .from("email_history")
        .update({ opened_at: new Date().toISOString(), open_count: Number(row.open_count || 0) + 1 })
        .eq("id", row.id);
    } else if (selectError) {
      console.error("[track-email-open] lookup failed:", selectError.message);
    }
  } catch (error) {
    console.error("[track-email-open] unexpected error:", error);
  }

  return pixelResponse(200);
});
