/**
 * Cliente API — Expedientes (referencia única de trazabilidad del trámite).
 */
import { api } from '$lib/api';

export interface Case {
	id: number;
	reference: string | null;
	account_id: number | null;
	title: string | null;
	stage: string;
	status: string;
	tenant_id: number;
	company_id: number;
	created_at: string;
	updated_at: string;
}

export interface CaseTimelineEvent {
	kind: string; // oportunidad | solicitud | cotizacion | operacion | factura
	id: number;
	reference: string | null;
	status: string | null;
	created_at: string;
	url: string;
}

export interface CaseWithTimeline extends Case {
	timeline: CaseTimelineEvent[];
}

function qp(companyId: number, extra?: Record<string, string | number | undefined>) {
	const qs = new URLSearchParams({ company_id: String(companyId) });
	for (const [k, v] of Object.entries(extra ?? {})) if (v !== undefined && v !== '') qs.set(k, String(v));
	return qs.toString();
}
async function unwrap<T>(p: Promise<{ data?: T; error?: string }>): Promise<T> {
	const res = await p;
	if (res.error) throw new Error(res.error);
	return res.data as T;
}

export const casesAPI = {
	list: (companyId: number, params?: { search?: string; account_id?: number; stage?: string }) =>
		unwrap<Case[]>(api.get(`/v1/crm/cases?${qp(companyId, params)}`)),
	get: (id: number, companyId: number) =>
		unwrap<CaseWithTimeline>(api.get(`/v1/crm/cases/${id}?${qp(companyId)}`)),
	byRef: (reference: string, companyId: number) =>
		unwrap<CaseWithTimeline>(api.get(`/v1/crm/cases/by-ref/${encodeURIComponent(reference)}?${qp(companyId)}`))
};
