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 scanLatency = new Trend('scan_p99');
const watchlistLatency = new Trend('watchlist_p99');
const alertLatency = new Trend('alert_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(200).thresholds,
    scan_p99: ['p(99)<300'],
    watchlist_p99: ['p(99)<200'],
    alert_p99: ['p(99)<250'],
  },
};

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

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

export default function () {
  group('Darkwatch Scan', function () {
    const payload = JSON.stringify({
      type: 'email',
      value: `loadtest-${randomString()}@example.com`,
    });
    const res = http.post(`${BASE_URL}/darkwatch/scan`, payload, { headers });
    checkResponse(res, 200);
    scanLatency.add(res.timings.duration);
  });

  group('Watchlist', function () {
    const res = http.get(`${BASE_URL}/watchlist?page=1&limit=20`, { headers });
    checkResponse(res, 200);
    watchlistLatency.add(res.timings.duration);
  });

  group('Alerts', function () {
    const res = http.get(`${BASE_URL}/alerts?status=open&limit=10`, { headers });
    checkResponse(res, 200);
    alertLatency.add(res.timings.duration);
  });

  group('Exposure Check', function () {
    const res = http.get(`${BASE_URL}/exposure/summary`, { headers });
    checkResponse(res, 200);
  });
}
