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

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

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

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

export default function () {
  const dbOperations = [
    { name: 'get-users', url: `${BASE_URL}/api/users` },
    { name: 'get-roles', url: `${BASE_URL}/api/roles` },
    { name: 'get-config', url: `${BASE_URL}/api/config` },
    { name: 'get-dict', url: `${BASE_URL}/api/dict` },
    { name: 'get-logs', url: `${BASE_URL}/api/oplog` },
  ];

  const operation = dbOperations[Math.floor(Math.random() * dbOperations.length)];

  const response = http.get(operation.url, {
    tags: { name: operation.name },
  });

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

  sleep(0.5);
}

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