/**
 * k6 load test — Agent Registration
 *
 * Scenario : POST /api/v1/agents
 * VUs      : 100
 * Duration : 60 seconds
 * Thresholds:
 *   p95 response time < 500 ms
 *   HTTP error rate   < 1 %
 *
 * Usage:
 *   BASE_URL=http://localhost:3000 k6 run tests/load/agent-registration.js
 */

import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';
import { uuidv4 } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js';

// ── Custom metrics ─────────────────────────────────────────────────────────────
const errorRate = new Rate('error_rate');
const registrationDuration = new Trend('registration_duration_ms', true);

// ── Configuration ──────────────────────────────────────────────────────────────
export const options = {
  vus: 100,
  duration: '60s',
  thresholds: {
    // p95 of all HTTP request durations must be below 500ms
    http_req_duration: ['p(95)<500'],
    // Custom error rate must be below 1%
    error_rate: ['rate<0.01'],
  },
};

const BASE_URL = __ENV.BASE_URL || 'http://localhost:3000';

// ── Default function (executed per VU iteration) ───────────────────────────────
export default function agentRegistration() {
  const url = `${BASE_URL}/api/v1/agents`;

  const payload = JSON.stringify({
    name: `load-test-agent-${uuidv4()}`,
    description: 'Created by k6 load test',
    deploymentEnvironment: 'load-test',
    capabilities: ['data-processing'],
    metadata: {
      loadTest: true,
      vu: __VU,
      iter: __ITER,
    },
  });

  const params = {
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    timeout: '10s',
  };

  const response = http.post(url, payload, params);

  // Record custom timing
  registrationDuration.add(response.timings.duration);

  // Validate response
  const success = check(response, {
    'status is 201': (r) => r.status === 201,
    'response has agentId': (r) => {
      try {
        const body = JSON.parse(r.body);
        return typeof body.agentId === 'string' && body.agentId.length > 0;
      } catch {
        return false;
      }
    },
    'response time < 500ms': (r) => r.timings.duration < 500,
  });

  errorRate.add(!success);

  // Brief think-time between iterations to avoid overwhelming the server
  sleep(0.1);
}
