import { API_KEY } from "@/lib/config";

export type AssignmentRole = "medico" | "enfermeiro";

export type PatientAssignment = {
  id: string;
  patient_id: string;
  user_id: string;
  role: AssignmentRole;
  created_at: string;
  created_by?: string | null;
};

export type CreatePatientAssignmentInput = {
  patient_id: string;
  user_id: string;
  role: AssignmentRole;
  created_by?: string | null;
};

const API_BASE =
  process.env.NEXT_PUBLIC_ASSIGNMENTS_API_BASE ??
  "https://mock.apidog.com/m1/1053378-0-default";
const REST = `${API_BASE}/rest/v1`;

function getAuthToken(): string | null {
  if (typeof window === "undefined") return null;
  return (
    localStorage.getItem("auth_token") ||
    localStorage.getItem("token") ||
    sessionStorage.getItem("auth_token") ||
    sessionStorage.getItem("token")
  );
}

function baseHeaders(): HeadersInit {
  const headers: Record<string, string> = {
    apikey: API_KEY,
    Accept: "application/json",
  };

  const token = getAuthToken();
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  return headers;
}

async function parseResponse<T>(response: Response): Promise<T> {
  let body: any = null;

  try {
    body = await response.json();
  } catch (error) {
    // Resposta sem corpo (204, etc.)
  }

  if (!response.ok) {
    const errorMessage =
      body?.message ||
      body?.error ||
      response.statusText ||
      "Erro ao comunicar com o serviço de atribuições";

    throw new Error(errorMessage);
  }

  return (body?.data ?? body) as T;
}

export async function listarAtribuicoesPacientes(options?: {
  patientId?: string;
  userId?: string;
}): Promise<PatientAssignment[]> {
  const query = new URLSearchParams();

  if (options?.patientId) {
    query.set("patient_id", `eq.${options.patientId}`);
  }

  if (options?.userId) {
    query.set("user_id", `eq.${options.userId}`);
  }

  const queryString = query.toString();
  const url = `${REST}/patient_assignments${queryString ? `?${queryString}` : ""}`;

  const response = await fetch(url, {
    method: "GET",
    headers: baseHeaders(),
  });

  return parseResponse<PatientAssignment[]>(response);
}

export async function criarAtribuicaoPaciente(
  input: CreatePatientAssignmentInput,
): Promise<PatientAssignment> {
  const url = `${REST}/patient_assignments`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      ...baseHeaders(),
      "Content-Type": "application/json",
      Prefer: "return=representation",
    },
    body: JSON.stringify(input),
  });

  const data = await parseResponse<PatientAssignment[] | PatientAssignment>(
    response,
  );

  return Array.isArray(data) ? data[0] : data;
}
