import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
  ForbiddenException,
  Logger,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { CapabilityService } from '@/application/services/capability.service';
import { Capability } from '@/domain/value-objects/capability.vo';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  private readonly logger = new Logger(JwtAuthGuard.name);

  constructor(
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
    private readonly capabilityService: CapabilityService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);

    if (!token) {
      throw new UnauthorizedException('未提供访问令牌');
    }

    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: this.configService.get<string>('JWT_SECRET'),
      });

      // 将用户信息附加到请求对象
      request.user = {
        accountSequence: payload.sub,
        phone: payload.phone,
        source: payload.source,
      };

      // 检查 LOGIN 能力 — 禁用后立即阻断所有已认证请求（强制下线）
      try {
        const loginEnabled = await this.capabilityService.isCapabilityEnabled(
          payload.sub,
          Capability.LOGIN,
        );
        if (!loginEnabled) {
          throw new ForbiddenException('您的账户已被限制登录，请联系客服');
        }
      } catch (error) {
        // 如果是我们主动抛出的 ForbiddenException，直接向上传递
        if (error instanceof ForbiddenException) {
          throw error;
        }
        // 能力查询失败时放行（fail-open），避免影响正常用户
        this.logger.warn(`LOGIN 能力检查失败 (${payload.sub}): ${error?.message}`);
      }

      return true;
    } catch (error) {
      if (error instanceof ForbiddenException) {
        throw error;
      }
      throw new UnauthorizedException('访问令牌无效或已过期');
    }
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
