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

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

const reqDuration = new Trend('quick_req_duration', true);
const successRate = new Rate('quick_success_rate');
const requestErrors = new Counter('quick_errors');

export const options = {
  scenarios: {
    quick_failover: {
      executor: 'constant-vus',
      vus: 20,
      duration: '20s',
    },
  },
  thresholds: {
    quick_success_rate: [{ threshold: 'rate>0.90', abortOnFail: false }],
    quick_req_duration: [{ threshold: 'p(95)<500', abortOnFail: false }],
  },
};

// One pre-registered user so per-iteration cost is just a access-token-protected GET.
// Avoids bcrypt latency dominating the 20-second window.
export function setup() {
  const suffix = Math.random().toString(36).substring(2, 10);
  const email = `demo_${suffix}@tapper.local`;
  const password = 'DemoPass1234!';
  const username = `demo_${suffix}`;

  const reg = http.post(
    `${BASE_URL}/api/auth/register`,
    JSON.stringify({ username, email, password }),
    { headers: { 'Content-Type': 'application/json' } }
  );

  if (reg.status !== 201 && reg.status !== 200) {
    throw new Error(`register failed: ${reg.status} ${reg.body}`);
  }

  const token = reg.json('access_token') || reg.json('token');
  if (!token) throw new Error('no access token in register response');

  console.log('');
  console.log('================================================================');
  console.log('  QUICK FAILOVER DEMO (20s)');
  console.log('  At ~t+5s, run in another terminal:');
  console.log('    docker stop tapper-api-2-1');
  console.log('  Watch the success rate and request duration in the live HUD.');
  console.log('================================================================');
  console.log('');

  return { token };
}

export default function (data) {
  const res = http.get(`${BASE_URL}/api/profile`, {
    headers: { Authorization: `Bearer ${data.token}` },
    tags: { name: 'GET /api/profile' },
  });

  reqDuration.add(res.timings.duration);

  const ok = check(res, {
    'profile 200': (r) => r.status === 200,
  });
  successRate.add(ok);
  if (!ok) requestErrors.add(1);
}

export function teardown() {
  console.log('');
  console.log('Demo complete. Quick read of the headline metrics:');
  console.log('  quick_success_rate  - should sit >= 95% even with one instance dead');
  console.log('  quick_errors        - the small burst at the moment api-2 dies');
  console.log('  quick_req_duration  - p95 stays flat: api-1 absorbs the load');
}
