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");
    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 supabaseClient = createClient(
        Deno.env.get("SUPABASE_URL") ?? "",
        Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? Deno.env.get("SUPABASE_ANON_KEY") ?? ""
      );

      // Verify and update clicks
      const { data, error } = await supabaseClient
        .from("sent_history")
        .select("clicks")
        .eq("id", id)
        .single();
        
      if (error) {
        console.error("Error fetching sent_history:", error);
      }

      if (data && !error) {
        const { error: updateError } = await supabaseClient
          .from("sent_history")
          .update({ 
             clicks: (data.clicks || 0) + 1,
             last_clicked_at: new Date().toISOString() 
          })
          .eq("id", id);
          
        if (updateError) {
          console.error("Error updating sent_history:", updateError);
        }
          
        const { error: insertError } = await supabaseClient
          .from("click_events")
          .insert({
             sent_history_id: id,
             url_clicked: destinationUrl
          });
          
        if (insertError) {
          console.error("Error inserting into click_events:", insertError);
        }
      }
    }

    // Redirect user
    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("Error tracking click:", error);
    // Even if it fails, try to redirect if destination URL is known, or return error
    const url = new URL(req.url);
    const dest = url.searchParams.get("url");
    if (dest) {
        return new Response(null, { status: 302, headers: { Location: dest } });
    }
    return new Response("Internal Server Error", { status: 500 });
  }
});
