/**
 * Cliente API — Actividades CRM
 */
import { api } from '$lib/api';
import type { Activity, ActivityInput } from './types';

export const activitiesAPI = {
	async list(
		companyId: number,
		params?: {
			activity_type?: string;
			status?: string;
			account_id?: number;
			contact_id?: number;
			lead_id?: number;
			opportunity_id?: number;
		}
	): Promise<Activity[]> {
		const qs = new URLSearchParams({ company_id: String(companyId) });
		if (params?.activity_type) qs.set('activity_type', params.activity_type);
		if (params?.status) qs.set('status', params.status);
		if (params?.account_id) qs.set('account_id', String(params.account_id));
		if (params?.contact_id) qs.set('contact_id', String(params.contact_id));
		if (params?.lead_id) qs.set('lead_id', String(params.lead_id));
		if (params?.opportunity_id) qs.set('opportunity_id', String(params.opportunity_id));
		const res = await api.get<Activity[]>(`/v1/crm/activities?${qs}`);
		if (res.error) throw new Error(res.error);
		return res.data!;
	},

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

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

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

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