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

const baseUrl = __ENV.BASE_URL;
const drawNo = __ENV.DRAW_NO;
const hotNumber = __ENV.HOT_NUMBER || '8888';
const lineAmount = Number(__ENV.LINE_AMOUNT || '100');
const playerIds = (__ENV.PLAYER_IDS || '')
  .split(',')
  .map((s) => s.trim())
  .filter(Boolean);

if (!baseUrl || !drawNo || playerIds.length === 0) {
  throw new Error('Set BASE_URL, DRAW_NO, PLAYER_IDS (comma-separated)');
}

export const options = {
  scenarios: {
    oversell: {
      executor: 'constant-vus',
      vus: Math.min(playerIds.length, 200),
      duration: '45s',
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.15'],
    oversell_seen: ['count>0'],
    success_seen: ['count>0'],
  },
};

const oversellSeen = new Counter('oversell_seen');
const successSeen = new Counter('success_seen');

function body(playerId, iter) {
  return JSON.stringify({
    draw_id: drawNo,
    currency_code: 'NPR',
    client_trace_id: `race-${playerId}-${iter}-${Date.now()}`,
    lines: [{ number: hotNumber, play_code: 'big', amount: lineAmount }],
  });
}

export default function () {
  const playerId = playerIds[(__VU - 1) % playerIds.length];
  const res = http.post(`${baseUrl}/api/v1/ticket/place`, body(playerId, __ITER), {
    headers: {
      Authorization: `Bearer dev:${playerId}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  });

  let code = -1;
  try {
    code = res.json('code');
  } catch {
    // ignore
  }

  if (code === 0) {
    successSeen.add(1);
  }
  if (code === 4001) {
    oversellSeen.add(1);
  }

  check(res, {
    'structured response': (r) => r.status === 200 || r.status === 400,
  });
}
