import http from 'k6/http';
import { check, group } from 'k6';
import { Rate, Trend } from 'k6/metrics';
import { getBaseUrl, getTargetRps, getDuration, defaultThresholds, checkResponse, randomString } from '../lib/common.js';

const notificationLatency = new Trend('notification_p99');
const correlationLatency = new Trend('correlation_p99');

const TARGET_RPS = getTargetRps();
const DURATION = getDuration();

export const options = {
  scenarios: {
    sustained_load: {
      executor: 'constant-arrival-rate',
      duration: DURATION,
      rate: TARGET_RPS,
      preAllocatedVUs: 20,
      maxVUs: 100,
      startTime: '0s',
      exec: 'default',
      tags: { scenario: 'sustained_load' },
    },
  },
  thresholds: {
    ...defaultThresholds(250).thresholds,
    notification_p99: ['p(99)<500'],
    correlation_p99: ['p(99)<300'],
  },
};

const BASE_URL = getBaseUrl();
const AUTH_TOKEN = __ENV.API_TOKEN || '';

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${AUTH_TOKEN}`,
};

export default function () {
  group('API Health', function () {
    const res = http.get(`${BASE_URL}/health`, { headers });
    checkResponse(res, 200);
  });

  group('Notifications', function () {
    const payload = JSON.stringify({
      userId: `user-${randomString()}`,
      channel: 'email',
      message: 'Load test notification',
    });
    const res = http.post(`${BASE_URL}/notifications`, payload, { headers });
    checkResponse(res, 200);
    notificationLatency.add(res.timings.duration);
  });

  group('Correlation', function () {
    const res = http.get(`${BASE_URL}/correlation/events?limit=10`, { headers });
    checkResponse(res, 200);
    correlationLatency.add(res.timings.duration);
  });
}
