import { apiDelete, apiGet, apiPatch, apiPost, apiPut, apiRequest } from './apiClient.js';

export async function getInvoiceById(id) {
    return apiGet(`/api/Invoices/${id}`);
}

export async function updateInvoice(id, data) {
    await apiPut(`/api/Invoices/${id}`, data);
    return true;
}

export async function validateInvoice(id) {
    await apiPost(`/api/Invoices/${id}/validate`);
    return true;
}

export async function updateInvoiceStatus(id, status) {
    await apiPatch(`/api/Invoices/${id}/status`, { status });
    return true;
}

export async function addInvoiceLine(id, lineData) {
    return apiPost(`/api/Invoices/${id}/lines`, lineData);
}

export async function deleteInvoiceLine(invoiceId, lineId) {
    await apiDelete(`/api/Invoices/${invoiceId}/lines/${lineId}`);
    return true;
}

export async function updateInvoiceLine(invoiceId, lineId, data) {
    await apiPut(`/api/Invoices/${invoiceId}/lines/${lineId}`, data);
    return true;
}

export async function addPayment(invoiceId, paymentData) {
    return apiPost(`/api/Invoices/${invoiceId}/payments`, paymentData);
}

export async function getPayments(invoiceId) {
    return apiGet(`/api/Invoices/${invoiceId}/payments`);
}

export async function downloadInvoicePdf(invoiceNumber) {
    const response = await apiRequest(`/api/document/invoice/${encodeURIComponent(invoiceNumber)}/pdf`, {
        method: 'GET',
        headers: { Accept: 'application/pdf' },
        responseType: 'raw'
    });
    const contentType = response.headers.get('content-type') || '';
    if (!contentType.includes('application/pdf')) {
        const nonPdfBody = await response.text().catch(() => '');
        throw new Error(nonPdfBody || 'La API no devolvió un PDF válido.');
    }

    return await response.blob();
}

export async function deleteInvoice(id) {
    await apiDelete(`/api/Invoices/${id}`);
    return true;
}

export async function getInvoiceTemplates() {
    return apiGet('/api/Invoices/templates');
}

export async function getTemplateById(id) {
    return apiGet(`/api/Invoices/templates/${id}`);
}
