import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AiUsageTokenService } from '../services/token.service';

/**
 * Ingestion 端点的 Bearer token 校验。
 * 把解析出的 { tokenId, userId, organizationId } 写到 req.aiUsageContext
 */
@Injectable()
export class IngestionTokenGuard implements CanActivate {
  constructor(private readonly tokenService: AiUsageTokenService) {}

  async canActivate(ctx: ExecutionContext): Promise<boolean> {
    const req = ctx.switchToHttp().getRequest();
    const auth = (req.headers?.authorization ?? req.headers?.Authorization) as string | undefined;
    if (!auth || !auth.startsWith('Bearer ')) {
      throw new UnauthorizedException('AI_USAGE_INVALID_TOKEN');
    }
    const raw = auth.slice('Bearer '.length).trim();
    const ip = (req.headers?.['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim() ?? req.ip;
    const result = await this.tokenService.validate(raw, ip);
    if (!result) throw new UnauthorizedException('AI_USAGE_INVALID_TOKEN');
    req.aiUsageContext = result;
    return true;
  }
}
