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",
};

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });

  try {
    const { task_title, assigned_to_user_id, assigned_by_name } = await req.json();
    const authHeader = req.headers.get("Authorization") || req.headers.get("authorization") || "";

    if (!authHeader) {
      return new Response(JSON.stringify({ success: false, error: "Unauthorized" }), {
        status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabase = createClient(supabaseUrl, serviceKey);

    const { data: userData, error: userError } = await supabase.auth.admin.getUserById(assigned_to_user_id);
    if (userError || !userData?.user?.email) {
      return new Response(JSON.stringify({ success: false, error: "User email not found" }), {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    const recipientEmail = userData.user.email;
    const idempotencyKey = `task-${assigned_to_user_id}-${task_title}-${Date.now()}`;

    const { data: result, error: invokeErr } = await supabase.functions.invoke("send-transactional-email", {
      body: {
        templateName: "task-notification",
        recipientEmail,
        idempotencyKey,
        templateData: {
          taskTitle: task_title,
          assignedByName: assigned_by_name || "Admin",
          link: "https://avria.cloud/dashboard/tasks",
        },
      },
    });

    if (invokeErr) {
      console.error("send-transactional-email error:", invokeErr);
      return new Response(JSON.stringify({ success: false, error: invokeErr.message }), {
        status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    return new Response(JSON.stringify({ success: true, result }), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("Error:", error);
    return new Response(JSON.stringify({ success: false, error: (error as Error).message }), {
      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
