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

const BASE_URL = __ENV.BASE_URL || 'http://localhost:5019';
const TOKEN = __ENV.TOKEN || '';
const VUS = Number(__ENV.VUS || 10);
const DURATION = __ENV.DURATION || '2m';
const PAUSE_SECONDS = Number(__ENV.PAUSE_SECONDS || 0.5);

const headers = TOKEN
  ? { Authorization: `Bearer ${TOKEN}` }
  : {};

export const options = {
  scenarios: {
    courses_list: {
      executor: 'constant-vus',
      vus: VUS,
      duration: DURATION,
      exec: 'coursesList',
    },
    lectures_list: {
      executor: 'constant-vus',
      vus: VUS,
      duration: DURATION,
      exec: 'lecturesList',
    },
    user_stats: {
      executor: 'constant-vus',
      vus: VUS,
      duration: DURATION,
      exec: 'userStats',
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<1500'],
    checks: ['rate>0.95'],
  },
};

function request(path, tag) {
  const res = http.get(`${BASE_URL}${path}`, {
    headers,
    tags: { endpoint: tag },
  });

  check(res, {
    'status is 200': (r) => r.status === 200,
    'body is not empty': (r) => (r.body || '').length > 0,
  });

  sleep(PAUSE_SECONDS);
}

export function coursesList() {
  request('/api/v1/courses?page=1&pageSize=50', 'courses_list');
}

export function lecturesList() {
  request('/api/v1/lectures?page=1&pageSize=50', 'lectures_list');
}

export function userStats() {
  request('/api/v1/users/me/stats', 'user_stats');
}
