import { Module } from '@nestjs/common';
import {
  PrometheusModule,
  makeCounterProvider,
  makeHistogramProvider,
  makeGaugeProvider,
} from '@willsoto/nestjs-prometheus';
import { MetricsService } from './infrastructure/metrics.service';
import {
  GOODGO_API_REQUEST_DURATION,
  GOODGO_LISTINGS_CREATED_TOTAL,
  GOODGO_PAYMENTS_PROCESSED_TOTAL,
  GOODGO_ACTIVE_SUBSCRIPTIONS,
  GOODGO_SEARCH_QUERIES_TOTAL,
  HTTP_REQUESTS_TOTAL,
  DB_QUERY_DURATION,
  DB_POOL_ACTIVE_CONNECTIONS,
  SEARCH_QUERY_DURATION,
} from './metrics.constants';
import { HttpMetricsInterceptor } from './presentation/interceptors/http-metrics.interceptor';

@Module({
  imports: [
    PrometheusModule.register({
      path: '/metrics',
      defaultMetrics: { enabled: true },
    }),
  ],
  providers: [
    // ── HTTP Metrics ──
    makeHistogramProvider({
      name: GOODGO_API_REQUEST_DURATION,
      help: 'Duration of HTTP requests in seconds',
      labelNames: ['method', 'route', 'status_code'],
      buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
    }),
    makeCounterProvider({
      name: HTTP_REQUESTS_TOTAL,
      help: 'Total number of HTTP requests',
      labelNames: ['method', 'route', 'status_code'],
    }),

    // ── Database Metrics ──
    makeHistogramProvider({
      name: DB_QUERY_DURATION,
      help: 'Duration of database queries in seconds',
      labelNames: ['operation', 'model'],
      buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
    }),
    makeGaugeProvider({
      name: DB_POOL_ACTIVE_CONNECTIONS,
      help: 'Number of active database connections',
    }),

    // ── Search Metrics ──
    makeHistogramProvider({
      name: SEARCH_QUERY_DURATION,
      help: 'Duration of search queries in seconds',
      labelNames: ['collection', 'type'],
      buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
    }),
    makeCounterProvider({
      name: GOODGO_SEARCH_QUERIES_TOTAL,
      help: 'Total number of search queries',
      labelNames: ['collection', 'type'],
    }),

    // ── Business Metrics ──
    makeCounterProvider({
      name: GOODGO_LISTINGS_CREATED_TOTAL,
      help: 'Total number of listings created',
      labelNames: ['category'],
    }),
    makeCounterProvider({
      name: GOODGO_PAYMENTS_PROCESSED_TOTAL,
      help: 'Total number of payments processed',
      labelNames: ['status', 'method'],
    }),
    makeGaugeProvider({
      name: GOODGO_ACTIVE_SUBSCRIPTIONS,
      help: 'Number of active subscriptions',
      labelNames: ['plan'],
    }),

    // ── Services & Interceptors ──
    MetricsService,
    HttpMetricsInterceptor,
  ],
  exports: [PrometheusModule, MetricsService, HttpMetricsInterceptor],
})
export class MetricsModule {}
