/**
 * Cliente API — Oportunidades CRM
 */
import { api } from '$lib/api';
import type { Opportunity, OpportunityInput } from './types';

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

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

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

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

	/** Mueve la oportunidad a otra etapa (drag & drop del Kanban). */
	async move(id: number, stageId: number, companyId: number): Promise<Opportunity> {
		const res = await api.patch<Opportunity>(
			`/v1/crm/opportunities/${id}/move?company_id=${companyId}`,
			{ stage_id: stageId }
		);
		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/opportunities/${id}?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
	}
};
