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

const BASE_PATH = '/v1/a76/audit-log';

export interface AuditLog {
	spec_id: number;
	reference: string;
	procedure: string; // "Procedimiento"
	movement: string; // "Movimiento"
	username: string;
	date: string; // "YYYY-MM-DD"
	time: string; // "HH:MM:SS"
	timestamp: string; // ISO
	system: string;
	operation_type?: string;
	table_name?: string;
	old_values?: any;
	new_values?: any;
}

export interface AuditLogResponse {
	data: AuditLog[];
	total: number;
	page: number;
	page_size: number;
}

export interface AuditLogParams {
	company_id: number;
	page?: number;
	page_size?: number;
	search?: string;
	username?: string;
	procedure?: string;
	reference?: string;
	date_from?: string;
	date_to?: string;
}

export const AuditLogAPI = {
	getLogs: async (params: AuditLogParams): Promise<AuditLogResponse> => {
		const query = new URLSearchParams();
		query.set('company_id', String(params.company_id));
		if (params.page) query.append('page', params.page.toString());
		if (params.page_size) query.append('page_size', params.page_size.toString());
		if (params.search) query.append('search', params.search);
		if (params.username) query.append('username', params.username);
		if (params.procedure) query.append('procedure', params.procedure);
		if (params.reference) query.append('reference', params.reference);
		if (params.date_from) query.append('date_from', params.date_from);
		if (params.date_to) query.append('date_to', params.date_to);

		const response = await api.get<AuditLogResponse>(`${BASE_PATH}/bitacora?${query.toString()}`);
		if (response.error || !response.data) {
			throw new Error(response.error || 'Failed to fetch audit logs');
		}
		return response.data;
	},

	getProcedures: async (companyId: number): Promise<string[]> => {
		const response = await api.get<string[]>(
			`${BASE_PATH}/bitacora/procedimientos?company_id=${companyId}`
		);
		if (response.error || !response.data) {
			throw new Error(response.error || 'Failed to fetch procedures');
		}
		return response.data;
	},

	getDetail: async (specId: number, companyId: number): Promise<AuditLog> => {
		const response = await api.get<AuditLog>(
			`${BASE_PATH}/bitacora/${specId}/detalle?company_id=${companyId}`
		);
		if (response.error || !response.data) {
			throw new Error(response.error || 'Failed to fetch audit log detail');
		}
		return response.data;
	}
};
