/**
 * k6 load test specifically for rate limiting
 * Tests rate limit enforcement and recovery
 * 
 * Run:
 * k6 run load-tests/k6-rate-limit.js
 */

import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate } from 'k6/metrics';

const rateLimited = new Rate('rate_limited');

export const options = {
  stages: [
    { duration: '10s', target: 100 },  // Rapid ramp up to trigger rate limits
    { duration: '30s', target: 100 },  // Sustain load
    { duration: '10s', target: 0 },     // Ramp down
  ],
  thresholds: {
    rate_limited: ['rate>0'], // Expect some rate limiting
  },
};

const GATEWAY_URL = __ENV.GATEWAY_URL || 'http://localhost:3000';
const API_KEY = __ENV.API_KEY || 'test-key-ce67dabb0d4e27e3d72877c921b89cae';

export default function () {
  const headers = {
    'Content-Type': 'application/json',
    'x-api-key': API_KEY,
  };

  // Send rapid requests to trigger rate limiting
  const response = http.get(`${GATEWAY_URL}/api/runs`, { headers });
  
  check(response, {
    'request completed': (r) => r.status !== 0,
    'rate limit error has retry-after': (r) => {
      if (r.status === 429) {
        try {
          const data = JSON.parse(r.body);
          return data.retry_after_ms !== undefined;
        } catch {
          return false;
        }
      }
      return true;
    },
  });

  rateLimited.add(response.status === 429);
  
  sleep(0.1); // Minimal sleep to maximize request rate
}

