/**
 * Cliente API — Embudos y etapas CRM
 */
import { api } from '$lib/api';
import type { Pipeline, Stage } from './types';

export const pipelinesAPI = {
	async list(companyId: number): Promise<Pipeline[]> {
		const res = await api.get<Pipeline[]>(`/v1/crm/pipelines?company_id=${companyId}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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

export interface StageInput {
	pipeline_id: number;
	name: string;
	position?: number;
	probability?: number;
	is_won?: boolean;
	is_lost?: boolean;
}

export const stagesAPI = {
	async list(companyId: number, pipelineId?: number): Promise<Stage[]> {
		const qs = new URLSearchParams({ company_id: String(companyId) });
		if (pipelineId) qs.set('pipeline_id', String(pipelineId));
		const res = await api.get<Stage[]>(`/v1/crm/stages?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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