// Cliente HTTP ÚNICO para a API Plamev (service.plamev.com.br). Uso exclusivo no servidor:
// Route Handlers (src/app/api) e Server Actions (src/actions). Nunca importe em 'use client'.
import { API_URL, PROD } from "@/utils/constants/selectConstants";
import { TOKEN } from "@/utils/constants/serverConstants";

interface IOpcoesRequisicao {
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    body?: unknown;
    headers?: Record<string, string>;
    // Cache em segundos (fetch do Next). Omitido = sem cache.
    revalidate?: number;
}

export interface IRespostaPlamev<T = any> {
    ok: boolean;
    status: number;
    dados: T | null;
}

// Nunca lança: falha de rede ou JSON inválido vira { ok: false, status: 0 | status, dados: null }.
export async function plamevRequest<T = any>(rota: string, opcoes: IOpcoesRequisicao = {}): Promise<IRespostaPlamev<T>> {
    const { method = 'GET', body, headers = {}, revalidate: revalidateSolicitado } = opcoes;
    // Cache só em produção: no HM toda leitura vai direto à API, para o QA ver na hora o que muda no back/Gerenciador.
    const revalidate = PROD ? revalidateSolicitado : undefined;

    try {
        const response = await fetch(`${API_URL}${rota}`, {
            method,
            headers: { Authorization: TOKEN, ...headers },
            body: body === undefined ? undefined : JSON.stringify(body),
            ...(revalidate ? { next: { revalidate } } : { cache: 'no-store' as const }),
        });

        const dados = await response.json().catch(() => null);

        return { ok: response.ok, status: response.status, dados };
    } catch (error) {
        console.error(`[plamevApi] ${method} ${rota}:`, error);
        return { ok: false, status: 0, dados: null };
    }
}

// Para Route Handlers: repassa status e corpo JSON da API ao navegador.
export function respostaJson({ status, dados }: IRespostaPlamev): Response {
    if (status === 0) return Response.json({ erro: true }, { status: 502 });
    return Response.json(dados, { status });
}
