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

const errorRate = new Rate('errors');

export const options = {
  stages: [
    { duration: '1m', target: 50 },   // Warm up
    { duration: '2m', target: 200 },  // Ramp up to stress level
    { duration: '3m', target: 500 },  // High stress
    { duration: '2m', target: 1000 }, // Peak stress
    { duration: '2m', target: 500 },  // Scale down
    { duration: '2m', target: 0 },    // Ramp down
  ],
  thresholds: {
    http_req_duration: ['p(95)<2000'], // 95% of requests should be below 2s under stress
    errors: ['rate<0.05'],            // Error rate should be less than 5% under stress
  },
};

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

export default function () {
  // Stress test with concurrent emergency alerts
  const emergencyPayload = JSON.stringify({
    latitude: 40.7128 + (Math.random() - 0.5) * 0.1,
    longitude: -74.0060 + (Math.random() - 0.5) * 0.1,
    message: `Stress test emergency alert ${Math.random()}`,
    alert_type: 'immediate'
  });

  // Test without authentication (anonymous emergency)
  let emergencyResponse = http.post(`${BASE_URL}/api/v1/emergency/anonymous-alert`, emergencyPayload, {
    headers: { 'Content-Type': 'application/json' },
  });

  check(emergencyResponse, {
    'emergency alert under stress': (r) => r.status === 201 || r.status === 429, // Accept rate limiting
    'response time under stress < 5s': (r) => r.timings.duration < 5000,
  }) || errorRate.add(1);

  // Rapid location updates (simulating real-time tracking)
  const locationPayload = JSON.stringify({
    latitude: 40.7128 + (Math.random() - 0.5) * 0.01,
    longitude: -74.0060 + (Math.random() - 0.5) * 0.01
  });

  let locationResponse = http.post(`${BASE_URL}/api/v1/location/anonymous-update`, locationPayload, {
    headers: { 'Content-Type': 'application/json' },
  });

  check(locationResponse, {
    'location update under stress': (r) => r.status === 200 || r.status === 429,
    'location response time < 2s': (r) => r.timings.duration < 2000,
  }) || errorRate.add(1);

  // Test system health under stress
  if (Math.random() < 0.1) { // 10% of requests check health
    let healthResponse = http.get(`${BASE_URL}/health`);
    check(healthResponse, {
      'health check under stress': (r) => r.status === 200,
      'health check fast under stress': (r) => r.timings.duration < 500,
    }) || errorRate.add(1);
  }

  // Minimal sleep for maximum stress
  sleep(0.1);
}