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

const okLatency = new Trend('place_ok_latency', true);
const okCount = new Counter('place_ok_total');

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');
}

export const options = {
  scenarios: {
    bet_ramp: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '30s', target: 200 },
        { duration: '60s', target: 1000 },
        { duration: '30s', target: 1000 },
        { duration: '15s', target: 0 },
      ],
      gracefulRampDown: '10s',
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.05'],
    http_req_duration: ['p(99)<200'],
    place_ok_latency: ['p(99)<200'],
    place_ok_total: ['count>30000'],
  },
};

function payload(vu, iter) {
  const n = String(1000 + ((vu + iter) % 9000)).padStart(4, '0');
  return JSON.stringify({
    draw_id: drawNo,
    currency_code: 'NPR',
    client_trace_id: `k6-${__VU}-${__ITER}-${Date.now()}`,
    lines: [{ number: n, play_code: 'big', amount: 10 }],
  });
}

export default function () {
  const res = http.post(`${baseUrl}/api/v1/ticket/place`, payload(__VU, __ITER), {
    headers: {
      Authorization: `Bearer dev:${playerId}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    tags: { name: 'ticket_place' },
  });

  const ok = check(res, {
    'status 200': (r) => r.status === 200,
    'code success': (r) => {
      try {
        return r.json('code') === 0;
      } catch {
        return false;
      }
    },
  });

  if (ok) {
    okLatency.add(res.timings.duration);
    okCount.add(1);
  }

  sleep(0.01);
}
