/**
 * Cliente API — Documentos CRM (de un cliente o proveedor)
 */
import { api } from '$lib/api';
import type { Document, DocumentInput } from './types';

export const documentsAPI = {
	async list(
		companyId: number,
		params?: { account_id?: number; supplier_id?: number }
	): Promise<Document[]> {
		const qs = new URLSearchParams({ company_id: String(companyId) });
		if (params?.account_id) qs.set('account_id', String(params.account_id));
		if (params?.supplier_id) qs.set('supplier_id', String(params.supplier_id));
		const res = await api.get<Document[]>(`/v1/crm/documents?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

	async create(data: DocumentInput, companyId: number): Promise<Document> {
		const res = await api.post<Document>(`/v1/crm/documents?company_id=${companyId}`, data);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

	async update(id: number, data: Partial<DocumentInput>, companyId: number): Promise<Document> {
		const res = await api.patch<Document>(`/v1/crm/documents/${id}?company_id=${companyId}`, data);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

	async remove(id: number, companyId: number): Promise<void> {
		const res = await api.delete(`/v1/crm/documents/${id}?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
	}
};
