/**
 * Basic k6 load test for the 4Runr Gateway
 * 
 * Prerequisites:
 * - Install k6: https://k6.io/docs/getting-started/installation/
 * - Set GATEWAY_URL environment variable (default: http://localhost:3000)
 * - Set API_KEY environment variable
 * 
 * Run:
 * k6 run load-tests/k6-basic.js
 */

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

// Custom metrics
const errorRate = new Rate('errors');
const requestDuration = new Trend('request_duration');
const requestsTotal = new Counter('requests_total');

// Test configuration
export const options = {
  stages: [
    { duration: '30s', target: 10 },   // Ramp up to 10 users
    { duration: '1m', target: 10 },      // Stay at 10 users
    { duration: '30s', target: 50 },    // Ramp up to 50 users
    { duration: '1m', target: 50 },     // Stay at 50 users
    { duration: '30s', target: 0 },     // Ramp down to 0 users
  ],
  thresholds: {
    http_req_duration: ['p(95)<500', 'p(99)<1000'], // 95% of requests < 500ms, 99% < 1s
    http_req_failed: ['rate<0.01'],                  // Less than 1% errors
    errors: ['rate<0.01'],
  },
};

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,
  };

  // Test 1: Health check (should be fast)
  const healthResponse = http.get(`${GATEWAY_URL}/health`, { headers });
  check(healthResponse, {
    'health check status is 200': (r) => r.status === 200,
    'health check response time < 100ms': (r) => r.timings.duration < 100,
  });
  errorRate.add(healthResponse.status >= 400);
  requestDuration.add(healthResponse.timings.duration);
  requestsTotal.add(1);
  sleep(0.1);

  // Test 2: List runs (read operation)
  const listResponse = http.get(`${GATEWAY_URL}/api/runs`, { headers });
  check(listResponse, {
    'list runs status is 200': (r) => r.status === 200,
    'list runs has runs array': (r) => {
      try {
        const data = JSON.parse(r.body);
        return Array.isArray(data.runs);
      } catch {
        return false;
      }
    },
  });
  errorRate.add(listResponse.status >= 400);
  requestDuration.add(listResponse.timings.duration);
  requestsTotal.add(1);
  sleep(0.2);

  // Test 3: Create run (write operation)
  const createPayload = JSON.stringify({
    name: `Load Test Run ${__VU}-${__ITER}`,
    input: { test: 'load', vu: __VU, iter: __ITER },
  });
  const createResponse = http.post(`${GATEWAY_URL}/api/runs`, createPayload, { headers });
  check(createResponse, {
    'create run status is 201': (r) => r.status === 201,
    'create run has run ID': (r) => {
      try {
        const data = JSON.parse(r.body);
        return data.run && data.run.id;
      } catch {
        return false;
      }
    },
  });
  errorRate.add(createResponse.status >= 400);
  requestDuration.add(createResponse.timings.duration);
  requestsTotal.add(1);
  sleep(0.3);

  // Test 4: Get run (if we created one)
  if (createResponse.status === 201) {
    try {
      const createData = JSON.parse(createResponse.body);
      const runId = createData.run.id;
      
      const getResponse = http.get(`${GATEWAY_URL}/api/runs/${runId}`, { headers });
      check(getResponse, {
        'get run status is 200': (r) => r.status === 200,
        'get run has correct ID': (r) => {
          try {
            const data = JSON.parse(r.body);
            return data.run && data.run.id === runId;
          } catch {
            return false;
          }
        },
      });
      errorRate.add(getResponse.status >= 400);
      requestDuration.add(getResponse.timings.duration);
      requestsTotal.add(1);
    } catch (e) {
      // Ignore parse errors
    }
  }

  sleep(1); // Think time between iterations
}

// Summary is automatically generated by k6

