import { MemberState } from "@app/shared/types/member";
import { NextFunction, Request, Response } from "express";
import { stat } from "fs";

export const requireLogin = function (req: Request, res: Response, next: NextFunction) {
    if (req.user?.id)
        next();
    else
        res.sendStatus(401)
}

export function requireMemberState(state: MemberState) {
    return function (req: Request, res: Response, next: NextFunction) {
        if (req.user?.state === state)
            next();
        else
            res.status(403).send(`You must be a ${state} of the 17th RBN to access this resource`);
    }
}

export function requireRole(requiredRoles: string | string[]) {
    // Normalize the input to always be an array of lowercase required roles
    const normalizedRequiredRoles: string[] = Array.isArray(requiredRoles)
        ? requiredRoles.map(role => role.toLowerCase())
        : [requiredRoles.toLowerCase()];

    const DEV_ROLE = 'dev';

    return function (req: Request, res: Response, next: NextFunction) {
        if (!req.user || !req.user.roles) {
            // User is not authenticated or has no roles array
            return res.sendStatus(401);
        }

        const userRolesLowercase = req.user.roles.map(role => role.name.toLowerCase());

        // Check if the user has *any* of the required roles OR the 'dev' role
        const hasAccess = userRolesLowercase.some(userRole =>
            userRole === DEV_ROLE || normalizedRequiredRoles.includes(userRole)
        );

        if (hasAccess) {
            return next();
        } else {
            // User is authenticated but does not have the necessary permissions
            return res.sendStatus(403);
        }
    };
}