import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { PrismaService } from '../../infrastructure/database/prisma.service';

@Injectable()
export class MetricsInterceptor implements NestInterceptor {
  constructor(private readonly prisma: PrismaService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const start = Date.now();
    const req = context.switchToHttp().getRequest();

    return next.handle().pipe(
      tap(async () => {
        const duration = Date.now() - start;
        const res = context.switchToHttp().getResponse();
        // Fire-and-forget: don't block the response
        this.prisma.apiMetric.create({
          data: {
            path: req.route?.path || req.url?.split('?')[0] || '/',
            method: req.method,
            statusCode: res.statusCode,
            duration,
            userId: req.user?.id || req.adminUser?.id || null,
            ip: req.ip || null,
          },
        }).catch(() => {});
      }),
    );
  }
}
