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

const baseUrl = __ENV.BASE_URL;
const playerId = __ENV.PLAYER_ID;
const drawNo = __ENV.DRAW_NO;

if (!baseUrl || !playerId || !drawNo) {
  throw new Error('Set BASE_URL, PLAYER_ID, DRAW_NO (must already be sealed / past close_time)');
}

const sealedReject = new Counter('sealed_reject_2001');

export const options = {
  vus: 50,
  duration: '20s',
  thresholds: {
    sealed_reject_2001: ['count>400'],
    http_req_failed: ['rate<0.01'],
  },
};

export default function () {
  const res = http.post(
    `${baseUrl}/api/v1/ticket/place`,
    JSON.stringify({
      draw_id: drawNo,
      currency_code: 'NPR',
      client_trace_id: `seal-${__VU}-${__ITER}-${Date.now()}`,
      lines: [{ number: '1234', play_code: 'big', amount: 10 }],
    }),
    {
      headers: {
        Authorization: `Bearer dev:${playerId}`,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
    },
  );

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

  const rejected = check(res, {
    'http 400': (r) => r.status === 400,
    'code 2001': () => code === 2001,
  });

  if (rejected) {
    sealedReject.add(1);
  }
}
