/**
 * tapper — Smoke Test
 *
 * Quick sanity check to verify all critical endpoints are functional.
 * Runs 1-2 VUs for 30 seconds — suitable for CI or post-deploy validation.
 *
 * Endpoints exercised:
 *   - GET  /api/health
 *   - POST /api/auth/register
 *   - POST /api/auth/login
 *   - GET  /api/profile (authenticated)
 *   - GET  /api/leaderboard (authenticated)
 *
 * Run:  k6 run loadtest/smoke-test.js
 */

import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { Rate } from 'k6/metrics';
import {
  registerUser,
  loginUser,
  authGet,
  getBaseUrl,
  randomUsername,
  randomEmail,
} from './helpers/auth.js';

const smokeSuccess = new Rate('smoke_success_rate');

export const options = {
  scenarios: {
    smoke: {
      executor: 'constant-vus',
      vus: 2,
      duration: '30s',
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<1000'],   // generous for smoke
    http_req_failed: ['rate<0.05'],       // allow up to 5 % in smoke
    smoke_success_rate: ['rate>0.95'],
  },
};

export function setup() {
  const BASE_URL = getBaseUrl();
  const res = http.get(`${BASE_URL}/api/health`);
  const ok = check(res, {
    'setup: health reachable': (r) => r.status === 200,
  });
  if (!ok) {
    console.error('Health endpoint not reachable — is the server running?');
  }
  return { baseUrl: BASE_URL };
}

export default function () {
  const BASE_URL = getBaseUrl();

  // ── Health check ────────────────────────────────────────────────────────
  group('smoke: health', () => {
    const res = http.get(`${BASE_URL}/api/health`, {
      tags: { name: 'GET /api/health' },
    });
    const ok = check(res, {
      'health: status 200': (r) => r.status === 200,
    });
    smokeSuccess.add(ok);
  });

  sleep(0.5);

  // ── Register ────────────────────────────────────────────────────────────
  let email, password;

  group('smoke: register', () => {
    const result = registerUser();
    email = result.email;
    password = result.password;
    const ok = result.response.status === 200 || result.response.status === 201;
    smokeSuccess.add(ok);
    if (!ok) {
      console.warn(`Register failed: ${result.response.status} ${result.response.body}`);
    }
  });

  sleep(0.5);

  // ── Login ───────────────────────────────────────────────────────────────
  let token = null;

  group('smoke: login', () => {
    token = loginUser(email, password);
    const ok = token !== null;
    smokeSuccess.add(ok);
    if (!ok) {
      console.warn('Login failed during smoke test');
    }
  });

  if (!token) {
    sleep(1);
    return;
  }

  sleep(0.5);

  // ── Profile ─────────────────────────────────────────────────────────────
  group('smoke: profile', () => {
    const res = authGet('/api/profile', token, { name: 'GET /api/profile' });
    const ok = check(res, {
      'profile: status 200': (r) => r.status === 200,
      'profile: has username': (r) => {
        try { return r.json('username') !== undefined; } catch (_) { return false; }
      },
    });
    smokeSuccess.add(ok);
  });

  sleep(0.5);

  // ── Leaderboard ─────────────────────────────────────────────────────────
  group('smoke: leaderboard', () => {
    const res = authGet('/api/leaderboard', token, { name: 'GET /api/leaderboard' });
    const ok = check(res, {
      'leaderboard: status 200': (r) => r.status === 200,
    });
    smokeSuccess.add(ok);
  });

  sleep(1);
}

export function teardown() {
  console.log('Smoke test complete. All core endpoints verified.');
}
