import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthService } from '../auth.service';
import { PERMISSION_KEY } from '../decorators/require-permission.decorator';

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private authService: AuthService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(PERMISSION_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

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

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user || !user.userId) {
      throw new ForbiddenException('未授权访问');
    }

    // 获取用户角色并检查是否为超级管理员
    const userRoles = await this.authService.getUserRoles(user.userId);
    if (userRoles.includes('super_admin')) {
      return true;
    }

    // 获取用户的所有权限
    const userPermissions = await this.authService.getUserPermissions(user.userId);

    // OR 逻辑：满足其中任意一个权限即可
    const hasPermission = requiredPermissions.some(perm => userPermissions.includes(perm));

    if (!hasPermission) {
      throw new ForbiddenException(`缺少权限: ${requiredPermissions.join(' 或 ')}`);
    }

    return true;
  }
}

