/**
 * API para gestión de permisos individuales de usuario
 */

import { api } from '$lib/api';
import type { Permission } from './permissions';

export interface UserPermission {
	id: number;
	user_id: string;
	permission_id: number;
	company_id: number;
	tenant_id: number;
	is_granted: boolean;
	is_active: boolean;
	assigned_by?: string;
	expires_at?: string;
	created_at?: string;
	updated_at?: string;
	permission?: Permission;
}

export interface AssignUserPermissionData {
	user_id: string;
	permission_id: number;
	is_granted?: boolean;
	expires_at?: string;
}

export interface UserPermissionsListResponse {
	items: UserPermission[];
	total: number;
}

export interface EffectiveUserPermissions {
	user_id: string;
	company_id: number;
	role_permissions: Permission[];
	granted_permissions: Permission[];
	revoked_permissions: Permission[];
	effective_permissions: Permission[];
}

export const userPermissionsAPI = {
	/**
	 * Obtener permisos individuales de un usuario
	 */
	async getIndividual(userId: string, companyId: number): Promise<UserPermissionsListResponse> {
		const response = await api.get(
			`/v1/core/permissions/users/${userId}/permissions?company_id=${companyId}`
		);
		return response.data;
	},

	/**
	 * Obtener permisos efectivos de un usuario (roles + individuales - revocados)
	 */
	async getEffective(userId: string, companyId: number): Promise<EffectiveUserPermissions> {
		const response = await api.get(
			`/v1/core/permissions/users/${userId}/permissions/effective?company_id=${companyId}`
		);
		return response.data;
	},

	/**
	 * Asignar un permiso individual a un usuario
	 */
	async assign(
		userId: string,
		companyId: number,
		data: Omit<AssignUserPermissionData, 'user_id'>
	): Promise<UserPermission> {
		const response = await api.post(
			`/v1/core/permissions/users/${userId}/permissions?company_id=${companyId}`,
			data
		);
		return response.data;
	},

	/**
	 * Conceder un permiso extra a un usuario
	 */
	async grant(userId: string, companyId: number, permissionId: number): Promise<UserPermission> {
		return this.assign(userId, companyId, {
			permission_id: permissionId,
			is_granted: true
		});
	},

	/**
	 * Revocar un permiso específico (aunque venga del rol)
	 */
	async revoke(userId: string, companyId: number, permissionId: number): Promise<UserPermission> {
		return this.assign(userId, companyId, {
			permission_id: permissionId,
			is_granted: false
		});
	},

	/**
	 * Eliminar un permiso individual
	 */
	async remove(userId: string, companyId: number, permissionId: number): Promise<void> {
		await api.delete(
			`/v1/core/permissions/users/${userId}/permissions/${permissionId}?company_id=${companyId}`
		);
	}
};
