import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ADMIN_ROLES_KEY } from '../decorators/admin-roles.decorator';
import { AdminRole, hasAdminRole } from '../types/admin-role.enum';
import type { AdminUser } from '@prisma/client';

@Injectable()
export class AdminRolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<AdminRole[]>(ADMIN_ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles || requiredRoles.length === 0) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const adminUser = (request as any).adminUser as AdminUser | undefined;

    if (!adminUser) {
      throw new ForbiddenException('请先登录');
    }

    const hasRequiredRole = requiredRoles.some((role) => hasAdminRole(adminUser.role, role));
    if (!hasRequiredRole) {
      throw new ForbiddenException('权限不足');
    }

    return true;
  }
}
