import { NextFunction, Request, Response } from 'express';
import User from '../Features/auth/schema/user.schema';

export const authorization = (roles: string[]): any => {
  return async (req: Request, res: Response, next: NextFunction) => {
    try {
      const userId = req['currentUser']?.id;
      if (!userId) {
        return res.status(401).json({ message: 'Unauthorized' });
      }

      const user = await User.findById(userId);
      if (!user) {
        return res.status(403).json({ message: 'Forbidden' });
      }

      if (!roles.includes(user.role)) {
        return res.status(403).json({ message: 'Forbidden' });
      }

      if (user.status !== 'ACTIVE') {
        return res.status(403).json({ message: 'Account not active' });
      }

      req['staffUser'] = user;
      next();
    } catch {
      return res.status(403).json({ message: 'Denied (system error)' });
    }
  };
};
