import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, test } from "node:test";
import { createGameApiHandler } from "./game-api.mjs";

const dataDirectory = mkdtempSync(join(tmpdir(), "iwt-heal-api-"));
const api = createGameApiHandler({ dataDirectory });
const server = createServer((request, response) => {
  void api.handle(request, response, () => {
    response.statusCode = 404;
    response.end();
  });
});
let baseUrl;

before(async () => {
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  const address = server.address();
  baseUrl = `http://127.0.0.1:${address.port}`;
});

after(async () => {
  await new Promise((resolve) => server.close(resolve));
  api.close();
  rmSync(dataDirectory, { recursive: true, force: true });
});

async function json(path, init = {}) {
  const response = await fetch(`${baseUrl}${path}`, init);
  const body = await response.json();
  return { response, body };
}

function save(slotId, hunterName, bulldromeKills, highestRoguelikeRound, highestRogueTrialsEndlessKills) {
  return {
    schemaVersion: 5,
    slotId,
    hunterName,
    stats: { bossKills: { bulldrome: bulldromeKills }, highestRoguelikeRound, highestRogueTrialsEndlessKills },
  };
}

test("health endpoint reports persistent database readiness", async () => {
  const { response, body } = await json("/api/health");
  assert.equal(response.status, 200);
  assert.deepEqual(body, { ok: true, database: "ready" });
});

test("accounts, server saves, and top-five plus current rankings work end to end", async () => {
  const players = [];
  for (let index = 0; index < 6; index += 1) {
    const username = `hunter_${index}`;
    const registration = await json("/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ username, password: `long-password-${index}` }),
    });
    assert.equal(registration.response.status, 201);
    const token = registration.body.token;
    const kills = 60 - index * 10;
    const highestRound = 30 - index * 4;
    const highestEndlessKills = 24 - index * 3;
    const upload = await json("/api/saves/1", {
      method: "PUT",
      headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
      body: JSON.stringify({ save: save(1, `Hero ${index}`, kills, highestRound, highestEndlessKills) }),
    });
    assert.equal(upload.response.status, 200);
    players.push({ token, kills, highestRound, highestEndlessKills });
  }

  const current = players[5];
  const bossBoard = await json("/api/leaderboards/boss/bulldrome?slot=1", {
    headers: { Authorization: `Bearer ${current.token}` },
  });
  assert.equal(bossBoard.body.top.length, 5);
  assert.equal(bossBoard.body.top[0].value, 60);
  assert.equal(bossBoard.body.current.rank, 6);
  assert.equal(bossBoard.body.current.value, current.kills);

  const rogueBoard = await json("/api/leaderboards/roguelike?slot=1", {
    headers: { Authorization: `Bearer ${current.token}` },
  });
  assert.equal(rogueBoard.body.top.length, 5);
  assert.equal(rogueBoard.body.current.rank, 6);
  assert.equal(rogueBoard.body.current.value, current.highestRound);

  const endlessBoard = await json("/api/leaderboards/rogue-trials-endless?slot=1", {
    headers: { Authorization: `Bearer ${current.token}` },
  });
  assert.equal(endlessBoard.body.kind, "rogue-trials-endless");
  assert.equal(endlessBoard.body.top.length, 5);
  assert.equal(endlessBoard.body.top[0].value, 24);
  assert.equal(endlessBoard.body.current.rank, 6);
  assert.equal(endlessBoard.body.current.value, current.highestEndlessKills);

  const download = await json("/api/saves/1", {
    headers: { Authorization: `Bearer ${current.token}` },
  });
  assert.equal(download.body.save.hunterName, "Hero 5");
});

test("invalid credentials cannot access server saves", async () => {
  const login = await json("/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username: "hunter_0", password: "incorrect-password" }),
  });
  assert.equal(login.response.status, 401);
  const saves = await json("/api/saves");
  assert.equal(saves.response.status, 401);
});
