import { Trend, Rate } from 'k6/metrics';

export const errorRate = new Rate('error_rate');

export function getBaseUrl() {
  return __ENV.BASE_URL || 'http://localhost:3000';
}

export function getTargetRps() {
  return parseInt(__ENV.TARGET_RPS || '500', 10);
}

export function getDuration() {
  return __ENV.DURATION || '300s';
}

export function defaultThresholds(p99ms) {
  return {
    thresholds: {
      http_req_duration: [`p(99)<${p99ms}`],
      error_rate: ['rate<0.01'],
    },
  };
}

export function checkResponse(res, expectedStatus = 200) {
  const pass = check(res, {
    'status is expected': (r) => r.status === expectedStatus,
    'response time OK': (r) => r.timings.duration < 5000,
  });
  errorRate.add(!pass);
  return pass;
}

export function randomString(length = 10) {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

export const autoscaleMetric = new Trend('autoscale_vu_count');

export function recordAutoscaleMetric(vuCount) {
  autoscaleMetric.add(vuCount);
}
