/**
 * Cliente API — Catálogos de referencia del CRM (SAT/ISO + del cliente).
 * T2026-07-081/082.
 */
import { api, type ApiResponse } from '$lib/api';

export interface CatalogItem {
	id: number;
	catalog: string;
	code: string;
	label: string;
	parent_catalog?: string | null;
	parent_code?: string | null;
	tenant_id: number | null;
	sort_order: number;
	is_active: boolean;
	is_system: boolean;
	extra?: Record<string, unknown> | null;
}

export interface CatalogMeta {
	catalog: string;
	label: string;
	scope: 'global' | 'tenant';
	is_system: boolean;
	count: number;
}

export interface CatalogItemInput {
	code: string;
	label: string;
	parent_catalog?: string | null;
	parent_code?: string | null;
	sort_order?: number;
	is_active?: boolean;
}

function qp(companyId: number, extra?: Record<string, string | number | boolean | 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 referenceCatalogsAPI = {
	/** Metadata de todos los catálogos (para la pantalla de administración). */
	meta: (companyId: number) => unwrap<CatalogMeta[]>(api.get(`/v1/crm/catalogs?${qp(companyId)}`)),
	/** Opciones activas de un catálogo (global + del tenant), con dependiente opcional. */
	list: (catalog: string, companyId: number, parentCode?: string) =>
		unwrap<CatalogItem[]>(api.get(`/v1/crm/catalogs/${catalog}?${qp(companyId, { parent_code: parentCode })}`)),
	/** Todas las opciones incluyendo inactivas (administración). */
	listAll: (catalog: string, companyId: number) =>
		unwrap<CatalogItem[]>(api.get(`/v1/crm/catalogs/${catalog}?${qp(companyId, { include_inactive: true })}`)),
	create: (catalog: string, companyId: number, data: CatalogItemInput, scope: 'tenant' | 'global' = 'tenant') =>
		api.post(`/v1/crm/catalogs/${catalog}?${qp(companyId, { scope })}`, data) as Promise<ApiResponse<CatalogItem>>,
	update: (catalog: string, id: number, companyId: number, data: Partial<CatalogItemInput>) =>
		api.patch(`/v1/crm/catalogs/${catalog}/${id}?${qp(companyId)}`, data) as Promise<ApiResponse<CatalogItem>>,
	remove: (catalog: string, id: number, companyId: number) =>
		api.delete(`/v1/crm/catalogs/${catalog}/${id}?${qp(companyId)}`) as Promise<ApiResponse<void>>
};
