import { Request, Response, NextFunction } from 'express'
import { forbidden } from '../utils/apiError'

// Restrict a route to specific roles. Accepts admin and super_admin for any admin action.
export const authorize = (...roles: string[]) =>
  (req: Request, _res: Response, next: NextFunction) => {
    const user = (req as any).user
    if (!user) return next(forbidden())
    // super_admin always allowed; admin allowed wherever staff/admin is allowed.
    const allowed = roles.includes('admin') ? [...roles, 'super_admin'] : roles
    if (!allowed.includes(user.role) && user.role !== 'super_admin') {
      return next(forbidden('Anda tidak memiliki hak akses ke resource ini'))
    }
    next()
  }

// Convenience: any authenticated admin-level account.
export const requireAdmin = authorize('admin')
