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

export let options = {
  stages: [
    { duration: '1m', target: 20 },
    { duration: '2m', target: 50 },
    { duration: '2m', target: 100 },
    { duration: '2m', target: 50 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<1000'],
    http_req_failed: ['rate<0.01'],
  },
};

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

export function setup() {
  console.log('Starting concurrent load test...');
  console.log(`Base URL: ${BASE_URL}`);
  console.log('Max concurrent users: 100');
}

export default function () {
  const scenarios = [
    {
      name: 'read-operations',
      weight: 0.7,
      operations: [
        { method: 'GET', url: `${BASE_URL}/api/users` },
        { method: 'GET', url: `${BASE_URL}/api/roles` },
        { method: 'GET', url: `${BASE_URL}/api/config` },
        { method: 'GET', url: `${BASE_URL}/api/dict` },
      ],
    },
    {
      name: 'write-operations',
      weight: 0.3,
      operations: [
        { method: 'POST', url: `${BASE_URL}/api/auth/login`, body: JSON.stringify({ username: 'admin', password: 'admin123' }) },
      ],
    },
  ];

  const scenario = scenarios[Math.random() < 0.7 ? scenarios[0] : scenarios[1]];
  const operation = scenario.operations[Math.floor(Math.random() * scenario.operations.length)];

  let response;
  if (operation.method === 'GET') {
    response = http.get(operation.url, {
      tags: { name: scenario.name },
    });
  } else if (operation.method === 'POST') {
    response = http.post(operation.url, operation.body, {
      tags: { name: scenario.name },
      headers: { 'Content-Type': 'application/json' },
    });
  }

  check(response, {
    'status is 200 or 201': (r) => r.status === 200 || r.status === 201,
    'response time < 1s': (r) => r.timings.duration < 1000,
    'operation successful': (r) => r.status < 400,
  });

  sleep(Math.random() * 2 + 1);
}

export function teardown(data) {
  console.log('Concurrent load test completed');
}