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

export const addressesAPI = {
	async list(
		companyId: number,
		params?: { account_id?: number; supplier_id?: number }
	): Promise<Address[]> {
		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<Address[]>(`/v1/crm/addresses?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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