import http from "k6/http";
import { check, sleep } from "k6";

const BASE_URL = __ENV.BASE_URL || "http://localhost:8000";
const ADMIN_EMAIL = __ENV.ADMIN_EMAIL || "admin@compton.example";
const ADMIN_PASSWORD = __ENV.ADMIN_PASSWORD || "Admin1234";

export const options = {
  stages: [
    { duration: "1m", target: 10 },
    { duration: "3m", target: 50 },
    { duration: "1m", target: 0 }
  ],
  thresholds: {
    http_req_duration: ["p(95)<300"],
    http_req_failed: ["rate<0.01"]
  }
};

export default function () {
  const roll = Math.random();

  if (roll < 0.35) {
    const res = http.get(`${BASE_URL}/api/v1/content/pages`);
    check(res, { "content list 200": (r) => r.status === 200 });
  } else if (roll < 0.6) {
    const res = http.post(
      `${BASE_URL}/api/v1/auth/login`,
      JSON.stringify({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
      { headers: { "Content-Type": "application/json" } }
    );
    check(res, { "login 200": (r) => r.status === 200 });
    if (res.status === 200) {
      const token = res.json("access_token");
      const me = http.get(`${BASE_URL}/api/v1/users/me`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      check(me, { "users me 200": (r) => r.status === 200 });
    }
  } else if (roll < 0.7) {
    const login = http.post(
      `${BASE_URL}/api/v1/auth/login`,
      JSON.stringify({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
      { headers: { "Content-Type": "application/json" } }
    );
    if (login.status === 200) {
      const refresh = http.post(`${BASE_URL}/api/v1/auth/refresh`, null, {
        headers: { Cookie: login.headers["Set-Cookie"] || "" }
      });
      check(refresh, { "refresh ok": (r) => r.status === 200 || r.status === 401 });
    }
  } else {
    const res = http.get(`${BASE_URL}/api/v1/content/pages/about`);
    check(res, { "content slug": (r) => r.status === 200 || r.status === 404 });
  }

  sleep(1);
}
