/**
 * Cliente API — Cuentas CRM
 */
import { api } from '$lib/api';
import type { Account, AccountInput } from './types';

export const accountsAPI = {
	async list(
		companyId: number,
		params?: { search?: string; status?: string }
	): Promise<Account[]> {
		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<Account[]>(`/v1/crm/accounts?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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

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