/** In-memory HTTP request counters for the /api/metrics endpoint. */

export interface RequestCountsSnapshot {
  total: number;
  by_status: Record<string, number>;
  errors_4xx: number;
  errors_5xx: number;
}

class RequestCounters {
  private total = 0;
  private byStatus: Record<number, number> = {};
  private errors4xx = 0;
  private errors5xx = 0;

  record(statusCode: number): void {
    this.total++;
    this.byStatus[statusCode] = (this.byStatus[statusCode] ?? 0) + 1;
    if (statusCode >= 400 && statusCode < 500) this.errors4xx++;
    else if (statusCode >= 500) this.errors5xx++;
  }

  snapshot(): RequestCountsSnapshot {
    const byStatus: Record<string, number> = {};
    for (const [code, count] of Object.entries(this.byStatus)) {
      byStatus[code] = count;
    }
    return {
      total: this.total,
      by_status: byStatus,
      errors_4xx: this.errors4xx,
      errors_5xx: this.errors5xx,
    };
  }
}

export const requestCounters = new RequestCounters();
