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

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

interface ExternalRest {
  from: (table: string) => any;
}

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 {
      patient_id,
      doctor_id,
      appointment_date,
      appointment_time,
      duration_minutes,
      reason,
      type,
    } = body;

    // 1. Criar no Supabase externo
    const externalData = await externalRest("appointments", "POST", {
      patient_id,
      doctor_id,
      appointment_date,
      appointment_time,
      duration_minutes: duration_minutes || 30,
      status: "scheduled",
      type: type || "consultation",
      reason,
    });

    const external_appointment_id = externalData[0]?.id;

    // 2. Log na nossa plataforma (user_actions)
    await supabase.from("user_actions").insert({
      user_id: user.id,
      external_user_id: patient_id,
      action_category: "appointment",
      action_type: "create",
      action_description: `Created appointment with doctor ${doctor_id}`,
      resource_type: "appointment",
      resource_id: external_appointment_id,
      new_data: { appointment_date, appointment_time, doctor_id, reason },
    });

    // 3. Enfileirar notificação de confirmação
    await supabase.from("notifications_queue").insert({
      recipient_id: patient_id,
      type: "sms",
      template: "appointment_created",
      data: { appointment_date, appointment_time, doctor_id },
      scheduled_for: new Date().toISOString(),
    });

    return new Response(
      JSON.stringify({ success: true, data: externalData[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" },
      }
    );
  }
});
