import { api } from '$lib/api';

export type UnifiedTaskStatus = 'pending' | 'active' | 'completed' | 'failed';

export interface UnifiedTask {
	task_id: string;
	task_name: string;
	task_group: string;
	task_origin?: string | null;
	status: UnifiedTaskStatus;
	celery_state_raw: string;
	progress: {
		current?: number | null;
		total?: number | null;
		percent?: number | null;
		message?: string | null;
	};
	retries?: number | null;
	error?: {
		type?: string | null;
		message?: string | null;
	} | null;
	tenant_id: number;
	requested_by_user?: string | null;
	started_at?: string | null;
	finished_at?: string | null;
	created_at: string;
	updated_at: string;
}

export interface UnifiedTaskDetail extends UnifiedTask {
	traceback_excerpt?: string | null;
	result_summary?: Record<string, unknown> | null;
	meta_payload?: Record<string, unknown> | null;
}

export interface UnifiedTaskListResponse {
	items: UnifiedTask[];
	total: number;
	page: number;
	page_size: number;
	has_next: boolean;
}

export interface UnifiedTaskCatalogs {
	task_groups: string[];
	task_names: string[];
	statuses: string[];
}

export const coreTasksApi = {
	list: (params?: {
		page?: number;
		page_size?: number;
		status?: UnifiedTaskStatus[];
		task_group?: string[];
		task_name?: string[];
		company_id?: number;
		search?: string;
		sync_active?: boolean;
	}) => {
		const qs = new URLSearchParams();
		if (params?.page) qs.set('page', String(params.page));
		if (params?.page_size) qs.set('page_size', String(params.page_size));
		if (params?.company_id != null) qs.set('company_id', String(params.company_id));
		if (params?.search) qs.set('search', params.search);
		if (params?.sync_active != null) qs.set('sync_active', String(params.sync_active));
		(params?.status || []).forEach((v) => qs.append('status', v));
		(params?.task_group || []).forEach((v) => qs.append('task_group', v));
		(params?.task_name || []).forEach((v) => qs.append('task_name', v));
		return api.get<UnifiedTaskListResponse>(`/v1/core/tasks?${qs.toString()}`);
	},
	get: (taskId: string, sync = true) =>
		api.get<UnifiedTaskDetail>(`/v1/core/tasks/${encodeURIComponent(taskId)}?sync=${String(sync)}`),
	sync: (taskIds?: string[]) => api.post<{ updated: number }>(`/v1/core/tasks/sync`, { task_ids: taskIds }),
	catalogs: () => api.get<UnifiedTaskCatalogs>(`/v1/core/tasks/catalogs`)
};
