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

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

export interface UserRole {
	id: number;
	user_id: string;
	company_id: number;
	company_role_id: number;
	is_active: boolean;
	created_at: string;
	assigned_by?: string;
	company_role?: {
		id: number;
		name: string;
		code: string;
		description?: string;
	};
	user?: {
		id: number;
		username: string;
		email?: string;
		full_name?: string;
	};
}

export interface AssignUserRoleData {
	user_id: string;
	company_role_id: number;
}

export interface UserRolesResponse {
	items: UserRole[];
	total: number;
	page: number;
	page_size: number;
}

export const userRolesAPI = {
	/**
	 * Listar todos los roles asignados a usuarios
	 */
	async list(
		companyId: number,
		params?: {
			user_id?: string;
			company_role_id?: number;
			page?: number;
			page_size?: number;
		}
	): Promise<UserRolesResponse> {
		const queryParams = new URLSearchParams();
		queryParams.set('company_id', companyId.toString());
		if (params?.user_id) queryParams.set('user_id', params.user_id);
		if (params?.company_role_id) queryParams.set('company_role_id', params.company_role_id.toString());
		if (params?.page) queryParams.set('page', params.page.toString());
		if (params?.page_size) queryParams.set('page_size', params.page_size.toString());
		const response = await api.get(`/v1/core/permissions/user-roles?${queryParams.toString()}`);
		return response.data;
	},

	/**
	 * Listar roles de un usuario específico
	 */
	async listByUser(userId: number, companyId: number): Promise<UserRolesResponse> {
		const response = await api.get(`/v1/core/permissions/users/${userId}/roles?company_id=${companyId}`);
		return response.data;
	},

	/**
	 * Listar usuarios con un rol específico
	 */
	async listByRole(roleId: number, companyId: number): Promise<UserRolesResponse> {
		const response = await api.get(`/v1/core/permissions/roles/${roleId}/users?company_id=${companyId}`);
		return response.data;
	},

	/**
	 * Asignar un rol a un usuario
	 */
	async assign(companyId: number, data: AssignUserRoleData): Promise<UserRole> {
		const response = await api.post(`/v1/core/permissions/user-roles?company_id=${companyId}`, data);
		return response.data;
	},

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