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 = { apikey: API_KEY, Accept: "application/json", }; const token = getAuthToken(); if (token) { headers.Authorization = `Bearer ${token}`; } return headers; } async function parseResponse(response: Response): Promise { 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 { 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(response); } export async function criarAtribuicaoPaciente( input: CreatePatientAssignmentInput, ): Promise { 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( response, ); return Array.isArray(data) ? data[0] : data; }