// server/utils/roleChecker.ts
// Utility functions for role-based access control

import { getSessionFromCookie } from './sessionStore';

/**
 * Check if user has a specific role
 */
export async function hasRole(event: any, role: string): Promise<boolean> {
    const session = await getSessionFromCookie(event);
    if (!session || !session.user) {
        return false;
    }
    
    const userRoles = session.user.roles || [];
    return userRoles.includes(role);
}

/**
 * Check if user has any of the specified roles
 */
export async function hasAnyRole(event: any, roles: string[]): Promise<boolean> {
    const session = await getSessionFromCookie(event);
    if (!session || !session.user) {
        return false;
    }
    
    const userRoles = session.user.roles || [];
    return roles.some(role => userRoles.includes(role));
}

/**
 * Check if user has all of the specified roles
 */
export async function hasAllRoles(event: any, roles: string[]): Promise<boolean> {
    const session = await getSessionFromCookie(event);
    if (!session || !session.user) {
        return false;
    }
    
    const userRoles = session.user.roles || [];
    return roles.every(role => userRoles.includes(role));
}

/**
 * Get all user roles
 */
export async function getUserRoles(event: any): Promise<string[]> {
    const session = await getSessionFromCookie(event);
    if (!session || !session.user) {
        return [];
    }
    
    return session.user.roles || [];
}

/**
 * Middleware helper to require specific role
 * Throws error if user doesn't have the required role
 */
export async function requireRole(event: any, role: string): Promise<void> {
    const hasRequiredRole = await hasRole(event, role);
    
    if (!hasRequiredRole) {
        throw createError({
            statusCode: 403,
            statusMessage: 'Forbidden',
            message: `Access denied. Required role: ${role}`
        });
    }
}

/**
 * Middleware helper to require any of the specified roles
 * Throws error if user doesn't have any of the required roles
 */
export async function requireAnyRole(event: any, roles: string[]): Promise<void> {
    const hasRequiredRole = await hasAnyRole(event, roles);
    
    if (!hasRequiredRole) {
        throw createError({
            statusCode: 403,
            statusMessage: 'Forbidden',
            message: `Access denied. Required roles: ${roles.join(', ')}`
        });
    }
}
