/**
 * API para gestión de permisos de roles
 */

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

export interface RolePermission {
	id: number;
	company_role_id: number;
	permission_id: number;
	granted_at?: string;
	granted_by?: number;
	tenant_id: number;
	permission?: {
		id: number;
		code: string;
		module: string;
		action: string;
		description?: string;
		is_active: boolean;
	};
}

export interface AssignPermissionData {
	permission_id: number;
}

export interface RolePermissionsResponse {
	role_id: number;
	permissions: RolePermission[];
	total: number;
}

export const rolePermissionsAPI = {
	/**
	 * Listar todos los permisos asignados a un rol
	 */
	async listByRole(roleId: number, companyId: number): Promise<RolePermissionsResponse> {
		const response = await api.get(`/v1/core/permissions/roles/${roleId}/permissions?company_id=${companyId}`);
		return response.data;
	},

	/**
	 * Asignar un permiso a un rol
	 */
	async assign(
		roleId: number,
		companyId: number,
		data: AssignPermissionData
	): Promise<RolePermission> {
		// El backend recibe permission_id como query param (no en el body).
		const response = await api.post(
			`/v1/core/permissions/roles/${roleId}/permissions?permission_id=${data.permission_id}&company_id=${companyId}`,
			{}
		);
		return response.data;
	},

	/**
	 * Remover un permiso de un rol
	 */
	async remove(roleId: number, permissionId: number, companyId: number): Promise<void> {
		await api.delete(`/v1/core/permissions/roles/${roleId}/permissions/${permissionId}?company_id=${companyId}`);
	},

	/**
	 * Asignar múltiples permisos a un rol
	 */
	async assignMultiple(
		roleId: number,
		companyId: number,
		permissionIds: number[]
	): Promise<RolePermission[]> {
		const response = await api.post(
			`/v1/core/permissions/roles/${roleId}/permissions/batch?company_id=${companyId}`,
			{ permission_ids: permissionIds }
		);
		return response.data;
	}
};
