/**
 * Cliente API — Prospectos CRM
 */
import { api } from '$lib/api';
import type { Lead, LeadConvertInput, LeadConvertResult, LeadInput } from './types';

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

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

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

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

	async convert(id: number, data: LeadConvertInput, companyId: number): Promise<LeadConvertResult> {
		const res = await api.post<LeadConvertResult>(
			`/v1/crm/leads/${id}/convert?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/leads/${id}?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
	}
};
