import http from 'k6/http';
import { check, group } from 'k6';
import { Rate } from 'k6/metrics';

// Test configuration
export const options = {
  stages: [
    { duration: '30s', target: 100 },    // Ramp up to 100 users
    { duration: '2m', target: 500 },      // Ramp to 500 req/s
    { duration: '3m', target: 500 },      // Stay at 500 req/s for 3 minutes
    { duration: '30s', target: 0 },       // Ramp down to 0
  ],
  thresholds: {
    http_req_duration: ['p(99)<200'],     // P99 latency < 200ms
    errors: ['rate<0.01'],                // Error rate < 1%
  },
};

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

export default function () {
  group('Watchlist Operations', function () {
    // GET /watchlist
    const watchlistRes = http.get(`${BASE_URL}/watchlist`, {
      headers: { 'Authorization': `Bearer ${getAuthToken()}` },
    });
    
    check(watchlistRes, {
      'watchlist GET status is 200': (r) => r.status === 200,
      'watchlist GET P99 < 100ms': (r) => r.timings.duration < 100,
    });

    // POST /watchlist
    const newItemRes = http.post(
      `${BASE_URL}/watchlist`,
      JSON.stringify({ type: 'email', value: `test${Date()}@example.com` }),
      {
        headers: { 
          'Authorization': `Bearer ${getAuthToken()}`,
          'Content-Type': 'application/json',
        },
      }
    );
    
  check(newItemRes, {
      'watchlist POST status is 201': (r) => r.status === 201,
      'watchlist POST P99 < 200ms': (r) => r.timings.duration < 200,
    });

    // POST /scan
    const scanRes = http.post(
      `${BASE_URL}/scan`,
      {},
      {
        headers: { 'Authorization': `Bearer ${getAuthToken()}` },
      }
    );
    
    check(scanRes, {
      'scan POST status is 200': (r) => r.status === 200,
      'scan POST P99 < 150ms': (r) => r.timings.duration < 150,
    });

    // GET /scan/schedule
    const scheduleRes = http.get(`${BASE_URL}/scan/schedule`, {
      headers: { 'Authorization': `Bearer ${getAuthToken()}` },
    });
    
 check(scheduleRes, {
      'schedule GET status is 200': (r) => r.status === 200,
      'schedule GET P99 < 100ms': (r) => r.timings.duration < 100,
    });

    // GET /exposures
    const exposuresRes = http.get(`${BASE_URL}/exposures`, {
      headers: { 'Authorization': `Bearer ${getAuthToken()}` },
    });
    
    check(exposuresRes, {
      'exposures GET status is 200': (r) => r.status === 200,
      'exposures GET P99 < 150ms': (r) => r.timings.duration < 150,
    });

    // GET /alerts
    const alertsRes = http.get(`${BASE_URL}/alerts`, {
      headers: { 'Authorization': `Bearer ${getAuthToken()}` },
    });
    
    check(alertsRes, {
      'alerts GET status is 200': (r) => r.status === 200,
      'alerts GET P99 < 150ms': (r) => r.timings.duration < 150,
    });
  });
}

// Helper function to get auth token (replace with actual token retrieval)
function getAuthToken() {
  return __ENV.AUTH_TOKEN || 'test-token';
}
