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

// Custom metrics
const errorRate = new Rate('errors');

export const options = {
  stages: [
    { duration: '2m', target: 100 }, // Ramp up to 100 users
    { duration: '5m', target: 100 }, // Stay at 100 users for 5 minutes
    { duration: '2m', target: 200 }, // Ramp up to 200 users
    { duration: '5m', target: 200 }, // Stay at 200 users for 5 minutes
    { duration: '2m', target: 0 },   // Ramp down to 0 users
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'], // 95% of requests should be below 500ms
    errors: ['rate<0.01'],           // Error rate should be less than 1%
  },
};

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

export default function () {
  // Test user registration
  const registrationPayload = JSON.stringify({
    email: `test_${Math.random()}@example.com`,
    password: 'testpassword123',
    first_name: 'Test',
    last_name: 'User',
    phone: '+1234567890'
  });

  let registrationResponse = http.post(`${BASE_URL}/api/v1/register`, registrationPayload, {
    headers: { 'Content-Type': 'application/json' },
  });

  check(registrationResponse, {
    'registration status is 201': (r) => r.status === 201,
    'registration response time < 2s': (r) => r.timings.duration < 2000,
  }) || errorRate.add(1);

  if (registrationResponse.status === 201) {
    const userData = JSON.parse(registrationResponse.body);
    
    // Test user login
    const loginPayload = JSON.stringify({
      email: userData.email,
      password: 'testpassword123'
    });

    let loginResponse = http.post(`${BASE_URL}/api/v1/login`, loginPayload, {
      headers: { 'Content-Type': 'application/json' },
    });

    check(loginResponse, {
      'login status is 200': (r) => r.status === 200,
      'login response time < 1s': (r) => r.timings.duration < 1000,
    }) || errorRate.add(1);

    if (loginResponse.status === 200) {
      const loginData = JSON.parse(loginResponse.body);
      const token = loginData.access_token;

      // Test authenticated endpoints
      const authHeaders = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      };

      // Get user profile
      let profileResponse = http.get(`${BASE_URL}/api/v1/profile`, { headers: authHeaders });
      check(profileResponse, {
        'profile status is 200': (r) => r.status === 200,
        'profile response time < 500ms': (r) => r.timings.duration < 500,
      }) || errorRate.add(1);

      // Test emergency alert (high load scenario)
      const emergencyPayload = JSON.stringify({
        latitude: 40.7128,
        longitude: -74.0060,
        message: 'Load test emergency alert',
        alert_type: 'immediate'
      });

      let emergencyResponse = http.post(`${BASE_URL}/api/v1/emergency/alert`, emergencyPayload, { headers: authHeaders });
      check(emergencyResponse, {
        'emergency alert status is 201': (r) => r.status === 201,
        'emergency alert response time < 1s': (r) => r.timings.duration < 1000,
      }) || errorRate.add(1);

      // Test location update
      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/update`, locationPayload, { headers: authHeaders });
      check(locationResponse, {
        'location update status is 200': (r) => r.status === 200,
        'location update response time < 300ms': (r) => r.timings.duration < 300,
      }) || errorRate.add(1);
    }
  }

  // Test health endpoints
  let healthResponse = http.get(`${BASE_URL}/health`);
  check(healthResponse, {
    'health check status is 200': (r) => r.status === 200,
    'health check response time < 100ms': (r) => r.timings.duration < 100,
  }) || errorRate.add(1);

  sleep(1);
}