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

export let options = {
  stages: [
    { duration: '30s', target: 10 },
    { duration: '1m', target: 20 },
    { duration: '30s', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.01'],
  },
};

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

export function setup() {
  console.log('Starting API performance test...');
  console.log(`Base URL: ${BASE_URL}`);
}

export default function () {
  const endpoints = [
    { method: 'GET', url: `${BASE_URL}/api/health` },
    { method: 'GET', url: `${BASE_URL}/api/users` },
    { method: 'GET', url: `${BASE_URL}/api/roles` },
    { method: 'GET', url: `${BASE_URL}/api/config` },
  ];

  const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];

  let response;
  if (endpoint.method === 'GET') {
    response = http.get(endpoint.url, {
      tags: { name: endpoint.url },
    });
  }

  check(response, {
    'status is 200': (r) => r.status === 200,
    'response time < 500ms': (r) => r.timings.duration < 500,
    'response body is not empty': (r) => r.body.length > 0,
  });

  sleep(1);
}

export function teardown(data) {
  console.log('API performance test completed');
}