/**
 * Cliente API — Contactos CRM
 */
import { api } from '$lib/api';
import type { Contact, ContactInput } from './types';

export const contactsAPI = {
	async list(
		companyId: number,
		params?: { search?: string; account_id?: number; supplier_id?: number }
	): Promise<Contact[]> {
		const qs = new URLSearchParams({ company_id: String(companyId) });
		if (params?.search) qs.set('search', params.search);
		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<Contact[]>(`/v1/crm/contacts?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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

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