import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { finalize, Observable } from 'rxjs';

const DEFAULT_API_SLOW_REQUEST_MS = 1000;

export function resolveApiSlowRequestThreshold(): number {
  const parsed = Number(process.env.API_SLOW_REQUEST_MS);
  if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_API_SLOW_REQUEST_MS;
  return Math.floor(parsed);
}

@Injectable()
export class ApiTimingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(ApiTimingInterceptor.name);
  private readonly thresholdMs = resolveApiSlowRequestThreshold();

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const startedAt = Date.now();
    return next.handle().pipe(
      finalize(() => {
        const durationMs = Date.now() - startedAt;
        if (durationMs < this.thresholdMs) return;

        const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
        const method = request.method ?? 'UNKNOWN';
        const url = request.originalUrl ?? request.url ?? 'unknown-url';
        this.logger.warn(`Slow API request: ${method} ${url} ${durationMs}ms`);
      }),
    );
  }
}
