/**
 * Helper para acessar o SUPABASE EXTERNO (fonte da verdade)
 * URL: https://yuanqfswhberkoevtmfr.supabase.co
 *
 * USAR PARA:
 * - appointments (CRUD)
 * - doctors (leitura)
 * - patients (leitura)
 * - reports (leitura/escrita)
 */

/// <reference lib="deno.ns" />

const EXTERNAL_SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const EXTERNAL_SUPABASE_ANON_KEY =
  Deno.env.get("EXTERNAL_SUPABASE_ANON_KEY") ||
  Deno.env.get("EXTERNAL_SUPABASE_KEY") ||
  "";

export async function externalRest(
  path: string,
  method: "GET" | "POST" | "PATCH" | "DELETE" = "GET",
  body?: Record<string, unknown>,
  authToken?: string
): Promise<Record<string, unknown> | Record<string, unknown>[]> {
  const url = `${EXTERNAL_SUPABASE_URL}/rest/v1/${path}`;

  const headers: Record<string, string> = {
    apikey: EXTERNAL_SUPABASE_ANON_KEY,
    "Content-Type": "application/json",
  };

  if (authToken) {
    headers["Authorization"] = authToken;
  }

  const options: RequestInit = {
    method,
    headers,
  };

  if (body && (method === "POST" || method === "PATCH")) {
    options.body = JSON.stringify(body);
  }

  const response = await fetch(url, options);

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`External Supabase error: ${error}`);
  }

  return await response.json();
}

/**
 * Buscar appointments do Supabase externo
 */
export async function getExternalAppointments(
  filters?: {
    doctor_id?: string;
    patient_id?: string;
    date?: string;
    status?: string;
  },
  authToken?: string
) {
  let path = "appointments?select=*";

  if (filters?.doctor_id) path += `&doctor_id=eq.${filters.doctor_id}`;
  if (filters?.patient_id) path += `&patient_id=eq.${filters.patient_id}`;
  if (filters?.date)
    path += `&scheduled_at=gte.${filters.date}T00:00:00&scheduled_at=lte.${filters.date}T23:59:59`;
  if (filters?.status) path += `&status=eq.${filters.status}`;

  return await externalRest(path, "GET", undefined, authToken);
}

/**
 * Criar appointment no Supabase externo
 */
export async function createExternalAppointment(
  data: {
    doctor_id: string;
    patient_id: string;
    scheduled_at: string; // ISO 8601 timestamp
    duration_minutes?: number;
    appointment_type?: string;
    status?: string;
    chief_complaint?: string;
    patient_notes?: string;
    created_by: string;
  },
  authToken?: string
) {
  return await externalRest("appointments", "POST", data, authToken);
}

/**
 * Atualizar appointment no Supabase externo
 */
export async function updateExternalAppointment(
  id: string,
  data: Partial<{
    scheduled_at: string;
    duration_minutes: number;
    appointment_type: string;
    status: string;
    notes: string;
    chief_complaint: string;
  }>,
  authToken?: string
) {
  return await externalRest(
    `appointments?id=eq.${id}`,
    "PATCH",
    data,
    authToken
  );
}

/**
 * Buscar doctors do Supabase externo
 */
export async function getExternalDoctors(
  filters?: {
    specialty?: string;
    active?: boolean;
  },
  authToken?: string
) {
  let path = "doctors?select=*";

  if (filters?.specialty) path += `&specialty=eq.${filters.specialty}`;
  if (filters?.active !== undefined) path += `&active=eq.${filters.active}`;

  return await externalRest(path, "GET", undefined, authToken);
}

/**
 * Buscar patients do Supabase externo
 */
export async function getExternalPatients(
  filters?: {
    id?: string;
    cpf?: string;
  },
  authToken?: string
) {
  let path = "patients?select=*";

  if (filters?.id) path += `&id=eq.${filters.id}`;
  if (filters?.cpf) path += `&cpf=eq.${filters.cpf}`;

  return await externalRest(path, "GET", undefined, authToken);
}

/**
 * Buscar reports do Supabase externo
 */
export async function getExternalReports(
  filters?: {
    patient_id?: string;
    doctor_id?: string;
    date_from?: string;
    date_to?: string;
  },
  authToken?: string
) {
  let path = "reports?select=*";

  if (filters?.patient_id) path += `&patient_id=eq.${filters.patient_id}`;
  if (filters?.doctor_id) path += `&doctor_id=eq.${filters.doctor_id}`;
  if (filters?.date_from) path += `&created_at=gte.${filters.date_from}`;
  if (filters?.date_to) path += `&created_at=lte.${filters.date_to}`;

  return await externalRest(path, "GET", undefined, authToken);
}
