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)<2000'],
    http_req_failed: ['rate<0.02'],
  },
};

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

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

export default function () {
  const pages = [
    '/',
    '/login',
    '/dashboard',
    '/system/config',
    '/system/dict',
    '/system/notice',
    '/oplog',
    '/loginlog',
    '/files',
  ];

  const page = pages[Math.floor(Math.random() * pages.length)];
  const url = `${BASE_URL}${page}`;

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

  check(response, {
    'status is 200': (r) => r.status === 200,
    'response time < 2s': (r) => r.timings.duration < 2000,
    'page loads successfully': (r) => r.body.length > 0,
  });

  sleep(2);
}

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