/**
 * API para gestión de roles por compañía
 */

import { api, type ApiResponse } from '$lib/api';

export interface CompanyRole {
	id: number;
	name: string;
	code: string;
	description?: string;
	is_active: boolean;
	company_id: number;
	tenant_id: number;
	created_at?: string;
	updated_at?: string;
}

export interface CreateRoleData {
	name: string;
	code: string;
	description?: string;
	is_active?: boolean;
}

export interface UpdateRoleData {
	name?: string;
	code?: string;
	description?: string;
	is_active?: boolean;
}

export interface RoleListResponse {
	items: CompanyRole[];
	total: number;
	page: number;
	page_size: number;
}

export const rolesAPI = {
	/**
	 * Listar roles con filtros
	 */
	async list(
		companyId: number,
		params?: {
			page?: number;
			page_size?: number;
			is_active?: boolean;
			search?: string;
		}
	): Promise<ApiResponse<RoleListResponse>> {
		const queryParams = new URLSearchParams();
		queryParams.set('company_id', companyId.toString());
		if (params?.page) queryParams.set('page', params.page.toString());
		if (params?.page_size) queryParams.set('page_size', params.page_size.toString());
		if (params?.is_active !== undefined) queryParams.set('is_active', params.is_active.toString());
		if (params?.search) queryParams.set('search', params.search);
		return api.get(`/v1/core/permissions/roles?${queryParams.toString()}`);
	},

	/**
	 * Obtener un rol por ID
	 */
	async getById(id: number, companyId: number): Promise<ApiResponse<CompanyRole>> {
		return api.get(`/v1/core/permissions/roles/${id}?company_id=${companyId}`);
	},

	/**
	 * Crear un nuevo rol
	 */
	async create(companyId: number, data: CreateRoleData): Promise<ApiResponse<CompanyRole>> {
		return api.post(`/v1/core/permissions/roles?company_id=${companyId}`, data);
	},

	/**
	 * Actualizar un rol
	 */
	async update(id: number, companyId: number, data: UpdateRoleData): Promise<ApiResponse<CompanyRole>> {
		return api.patch(`/v1/core/permissions/roles/${id}?company_id=${companyId}`, data);
	},

	/**
	 * Eliminar un rol
	 */
	async delete(id: number, companyId: number): Promise<ApiResponse<void>> {
		return api.delete(`/v1/core/permissions/roles/${id}?company_id=${companyId}`);
	}
};
