/**
 * API para gestión de permisos del sistema
 */

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

export interface Permission {
	id: number;
	code: string;
	description?: string;
	module: string;
	action: string;
	is_active: boolean;
	created_at?: string;
	updated_at?: string;
}

export interface CreatePermissionData {
	code?: string;
	description?: string;
	module: string;
	action: string;
	is_active?: boolean;
}

export interface UpdatePermissionData {
	code?: string;
	description?: string;
	module?: string;
	action?: string;
	is_active?: boolean;
}

export interface PermissionListResponse {
	items: Permission[];
	total: number;
	page: number;
	page_size: number;
}

export const permissionsAPI = {
	/**
	 * Listar permisos con filtros
	 */
	async list(params?: {
		page?: number;
		page_size?: number;
		module?: string;
		action?: string;
		is_active?: boolean;
		search?: string;
	}): Promise<PermissionListResponse> {
		const queryParams = new URLSearchParams();
		if (params?.page) queryParams.set('page', params.page.toString());
		if (params?.page_size) queryParams.set('page_size', params.page_size.toString());
		if (params?.module) queryParams.set('module', params.module);
		if (params?.action) queryParams.set('action', params.action);
		if (params?.search) queryParams.set('search', params.search);
		const query = queryParams.toString();
		// Sin slash final: la ruta backend es @router.get("") = /v1/core/permissions.
		// Con slash FastAPI responde 307 y el cliente server-side no lo sigue.
		const response = await api.get(`/v1/core/permissions${query ? '?' + query : ''}`);
		return response.data;
	},

	/**
	 * Obtener un permiso por ID
	 */
	async getById(id: number): Promise<Permission> {
		const response = await api.get(`/v1/core/permissions/${id}`);
		return response.data;
	},

	/**
	 * Crear un nuevo permiso
	 */
	async create(data: CreatePermissionData): Promise<Permission> {
		const response = await api.post('/v1/core/permissions', data);
		return response.data;
	},

	/**
	 * Actualizar un permiso
	 */
	async update(id: number, data: UpdatePermissionData): Promise<Permission> {
		const response = await api.put(`/v1/core/permissions/${id}`, data);
		return response.data;
	},

	/**
	 * Eliminar un permiso
	 */
	async delete(id: number): Promise<void> {
		await api.delete(`/v1/core/permissions/${id}`);
	},

	/**
	 * Obtener módulos únicos
	 */
	async getModules(): Promise<string[]> {
		const response = await api.get('/v1/core/permissions/modules');
		return response.data;
	},

	/**
	 * Obtener acciones únicas
	 */
	async getActions(): Promise<string[]> {
		const response = await api.get('/v1/core/permissions/actions');
		return response.data;
	}
};
