import type { Request, Response, NextFunction } from 'express';
import { prisma } from '../config/database.js';

type Role = 'USER' | 'MODERATOR' | 'ADMIN' | 'SUPER_ADMIN';

const ROLE_HIERARCHY: Record<Role, number> = {
  USER: 0,
  MODERATOR: 1,
  ADMIN: 2,
  SUPER_ADMIN: 3,
};

export function requireRole(...roles: Role[]) {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    if (!req.userId) {
      res.status(401).json({ message: 'Authentication required' });
      return;
    }

    const user = await prisma.user.findUnique({
      where: { id: req.userId },
      select: { role: true, isBanned: true },
    });

    if (!user) {
      res.status(401).json({ message: 'User not found' });
      return;
    }

    if (user.isBanned) {
      res.status(403).json({ message: 'Account is suspended' });
      return;
    }

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

    (req as any).userRole = user.role;
    next();
  };
}

export const requireModerator = requireRole('MODERATOR', 'ADMIN', 'SUPER_ADMIN');
export const requireAdmin = requireRole('ADMIN', 'SUPER_ADMIN');
export const requireSuperAdmin = requireRole('SUPER_ADMIN');
