'use server'

import { API_URL } from "@/utils/constants/selectConstants";
import { TOKEN } from "@/utils/constants/serverConstants";

// Substitui o antigo cliente axios (src/services/api.ts), que rodava no navegador com o token.
async function requisitar(url: string, init?: { method?: string; body?: unknown }) {
    try {
        const response = await fetch(`${API_URL}${url}`, {
            method: init?.method ?? 'GET',
            headers: {
                Authorization: TOKEN,
                ...(init?.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
            },
            body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
            cache: 'no-store',
        });

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

        return { ok: response.ok, status: response.status, dados };
    } catch (error) {
        console.error(`Erro na requisição ${url}:`, error);
        return { ok: false, status: 0, dados: null };
    }
}

export async function inserirNewsletter(email: string) {
    return requisitar('SiteNewsletterInscritos/inserir', { method: 'POST', body: { email } });
}

export async function consultarCep(Cep: string) {
    return requisitar('IndividuosEnderecos/ConsultaCep', { method: 'POST', body: { Cep } });
}
