import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { SessionVault } from "../src/session/SessionVault.ts";
import type { SessionPayload } from "../src/types.ts";

const payload: SessionPayload = {
  version: 2,
  provider: "kick",
  accountUsername: "fiIyx",
  kickUserId: "12345",
  accessToken: "secret-access-token",
  refreshToken: "secret-refresh-token",
  tokenType: "Bearer",
  scopes: ["user:read", "chat:write"],
  expiresAt: "2026-07-28T01:00:00.000Z",
  lastValidatedAt: "2026-07-28T00:00:00.000Z"
};

test("le coffre chiffre et authentifie les jetons OAuth fiIyx", async () => {
  const directory = await mkdtemp(path.join(os.tmpdir(), "filyx-vault-"));
  const file = path.join(directory, "fiIyx-oauth.enc");
  const vault = new SessionVault(file, "11".repeat(32));
  await vault.save(payload);
  const encrypted = await readFile(file);
  assert.equal(encrypted.includes(Buffer.from("secret-access-token")), false);
  assert.equal(encrypted.includes(Buffer.from("secret-refresh-token")), false);
  assert.deepEqual(await vault.load(), payload);
  const wrong = new SessionVault(file, "22".repeat(32));
  await assert.rejects(() => wrong.load(), /Clé incorrecte|corrompu/);
});

test("le coffre refuse une identité différente", async () => {
  const directory = await mkdtemp(path.join(os.tmpdir(), "filyx-vault-"));
  const vault = new SessionVault(path.join(directory, "session.enc"), "33".repeat(32));
  await assert.rejects(() => vault.save({ ...payload, accountUsername: "viewer" as "fiIyx" }), /refusé/);
});
