// retoor <retoor@molodetz.nl>

import { DevRant } from "./client.mjs";

const base = process.env.DEVRANT_BASE || "http://localhost:10500";

let passed = 0;
let failed = 0;

function check(label, condition, detail = "") {
  if (condition) {
    passed += 1;
    console.log(`  PASS  ${label}`);
  } else {
    failed += 1;
    console.log(`  FAIL  ${label} ${detail}`);
  }
}

const suffix = String(Math.floor(Date.now() / 1000));
const username = `dr_smoke_${suffix}`;
const api = new DevRant(base, username, "secret6");

const reg = await api.register(`${username}@example.test`);
check("register", reg.success, JSON.stringify(reg));

const login = await new DevRant(base, username, "secret6").login();
check("login returns token", Boolean(login.token_key));
await api.login();

const posted = await api.postRant("Smoke test rant about Python", "python,smoke,devrant");
check("post rant", posted.success);
const rantId = posted.rant_id;

const feed = await api.rants("recent", 5);
check("feed returns rants", feed.some((r) => r.id === rantId));

const detail = await api.rant(rantId);
check("get rant tags round-trip", JSON.stringify(detail.rant.tags) === JSON.stringify(["python", "smoke", "devrant"]));
check("get rant editable", detail.rant.editable === true);

check("comment", (await api.comment(rantId, "Nice rant!")).success);

const voted = await api.voteRant(rantId, 1);
check("vote score", voted.rant.score === 1);
check("vote state", voted.rant.vote_state === 1);

check("favorite", (await api.favorite(rantId)).success);
check("unfavorite", (await api.unfavorite(rantId)).success);

const uid = await api.userId(username);
check("get-user-id", Boolean(uid));

let profile = await api.profile(uid);
check("profile score", profile.score === 1);
check("profile counts", profile.content.counts.rants === 1);

await api.editProfile({ profile_about: "I build with Python", profile_github: "smoke" });
profile = await api.profile(uid);
check("edit-profile bio", profile.about === "I build with Python");
check("skills derived from bio", profile.skills === "I build with Python");

const notifs = await api.notifs();
check("notif-feed shape", "unread" in notifs && "items" in notifs);

check("delete rant", (await api.deleteRant(rantId)).success);

let badRejected = false;
try {
  await new DevRant(base, username, "wrongpw").login();
} catch {
  badRejected = true;
}
check("bad login rejected", badRejected);

console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
