// MÓDULO 2.1: APPOINTMENTS - /appointments/update
import { validateExternalAuth } from "../_shared/auth.ts";

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

function externalRest(path: string, method: string, body?: any): Promise<any> {
  const url = `${Deno.env.get("EXTERNAL_SUPABASE_URL")}/rest/v1/${path}`;
  return fetch(url, {
    method,
    headers: {
      "Content-Type": "application/json",
      apikey: Deno.env.get("EXTERNAL_SUPABASE_KEY")!,
      Authorization: `Bearer ${Deno.env.get("EXTERNAL_SUPABASE_KEY")}`,
      Prefer: "return=representation",
    },
    body: body ? JSON.stringify(body) : undefined,
  }).then((r) => r.json());
}

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

  try {
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) throw new Error("Missing authorization");

    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_ANON_KEY")!,
      { global: { headers: { Authorization: authHeader } } }
    );

    const {
      data: { user },
      error: authError,
    } = await supabase.auth.getUser();
    if (authError || !user) throw new Error("Unauthorized");

    const body = await req.json();
    const { appointment_id, updates } = body;

    // Buscar dados antigos para auditoria
    const oldData = await externalRest(
      `appointments?id=eq.${appointment_id}`,
      "GET"
    );

    // Atualizar no Supabase externo
    const updatedData = await externalRest(
      `appointments?id=eq.${appointment_id}`,
      "PATCH",
      updates
    );

    // Log na nossa plataforma
    await supabase.from("user_actions").insert({
      user_id: user.id,
      external_user_id: oldData[0]?.patient_id,
      action_category: "appointment",
      action_type: "update",
      action_description: `Updated appointment ${appointment_id}`,
      resource_type: "appointment",
      resource_id: appointment_id,
      old_data: oldData[0],
      new_data: updatedData[0],
    });

    return new Response(
      JSON.stringify({ success: true, data: updatedData[0] }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  } catch (error: any) {
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      {
        status: 400,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  }
});
