import http from "k6/http";
import { check } from "k6";
import { Trend } from "k6/metrics";

const baseUrl = (__ENV.BASE_URL || "http://localhost:3000").replace(/\/+$/, "");
const username = __ENV.USERNAME || "alice";
const password = __ENV.PASSWORD || "alice123";
const jwtValidationRequests = Number(__ENV.JWT_VALIDATION_REQUESTS || 10000);
const jwtValidationVus = Number(__ENV.JWT_VALIDATION_VUS || 100);

const jwtValidationLatency = new Trend("jwt_validation_latency_ms");

export const options = {
  scenarios: {
    jwt_validation_benchmark: {
      executor: "shared-iterations",
      vus: jwtValidationVus,
      iterations: jwtValidationRequests,
      maxDuration: "30m"
    }
  },
  thresholds: {
    http_req_failed: ["rate<0.01"]
  },
  summaryTrendStats: ["avg", "min", "med", "p(90)", "p(95)", "max"]
};

export function setup() {
  const loginRes = http.post(
    `${baseUrl}/api/auth/login`,
    JSON.stringify({ username, password }),
    { headers: { "Content-Type": "application/json" } }
  );

  check(loginRes, { "jwt benchmark login success": (r) => r.status === 200 });
  if (loginRes.status !== 200) {
    throw new Error(`JWT benchmark login failed: status=${loginRes.status} body=${loginRes.body}`);
  }

  return { token: loginRes.json("token") };
}

export default function (data) {
  const res = http.get(`${baseUrl}/api/auth/validate`, {
    headers: { Authorization: `Bearer ${data.token}` }
  });
  jwtValidationLatency.add(res.timings.duration);
  check(res, { "jwt validate status 200": (r) => r.status === 200 });
}
