/**
 * Cliente API — Proveedores CRM
 */
import { api } from '$lib/api';
import type { Supplier, SupplierInput } from './types';

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

	async get(id: number, companyId: number): Promise<Supplier> {
		const res = await api.get<Supplier>(`/v1/crm/suppliers/${id}?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

	async update(id: number, data: Partial<SupplierInput>, companyId: number): Promise<Supplier> {
		const res = await api.patch<Supplier>(`/v1/crm/suppliers/${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/suppliers/${id}?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
	}
};
