import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { initialAccountsState, reduceAccountsState } from "./accounts-state.js";

test("account mutation tracks pending and clears prior error", () => {
  const state = reduceAccountsState({ ...initialAccountsState, error: "old" }, { type: "mutation.started", accountId: "a" });
  assert.deepEqual(state, { pending: true, pendingAccountId: "a", error: "" });
});

test("account rename tracks the pending account", () => {
  const state = reduceAccountsState(initialAccountsState, { type: "mutation.started", accountId: "account-a" });
  assert.deepEqual(state, { pending: true, pendingAccountId: "account-a", error: "" });
});

test("failed account mutation preserves safe error code", () => {
  const state = reduceAccountsState({ pending: true, pendingAccountId: "a", error: "" }, { type: "mutation.failed", error: "last_visible_account" });
  assert.deepEqual(state, { pending: false, pendingAccountId: "", error: "last_visible_account" });
});

test("completed account mutation clears pending state", () => {
  const state = reduceAccountsState({ pending: true, pendingAccountId: "a", error: "old" }, { type: "mutation.completed" });
  assert.deepEqual(state, initialAccountsState);
});

test("account mutation errors expose only allowlisted codes", async () => {
  const source = await readFile(new URL("./accounts-state.js", import.meta.url), "utf8");
  assert.match(source, /export function accountMutationError/);
  assert.match(source, /account_login_rate_limited/);
  assert.match(source, /return fallback/);
});
