import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export type ApiTier = 'public' | 'institutional' | 'regulatory' | 'internal';

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

  canActivate(context: ExecutionContext): boolean {
    const requiredTier = this.reflector.get<ApiTier>('apiTier', context.getHandler()) || 'public';
    const request = context.switchToHttp().getRequest();
    const apiKey = request.headers['x-api-key'];

    if (!apiKey) {
      throw new UnauthorizedException('Missing API key');
    }

    const tier = this.resolveApiKeyTier(apiKey);
    if (!tier) {
      throw new UnauthorizedException('Invalid API key');
    }

    const tierHierarchy: ApiTier[] = ['public', 'institutional', 'regulatory', 'internal'];
    const requiredLevel = tierHierarchy.indexOf(requiredTier);
    const actualLevel = tierHierarchy.indexOf(tier);

    if (actualLevel < requiredLevel) {
      throw new UnauthorizedException(`Insufficient API tier: requires ${requiredTier}`);
    }

    request.apiTier = tier;
    return true;
  }

  private resolveApiKeyTier(apiKey: string): ApiTier | null {
    // 生产环境从数据库/Redis查询API Key对应的tier
    // 此处简化为前缀判断
    if (apiKey.startsWith('gx_internal_')) return 'internal';
    if (apiKey.startsWith('gx_reg_')) return 'regulatory';
    if (apiKey.startsWith('gx_inst_')) return 'institutional';
    if (apiKey.startsWith('gx_pub_')) return 'public';
    return null;
  }
}
