import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, statSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadOrCreateToken } from "../src/token";

let dir: string;
const originalEnv = process.env.OVERDECK_CONFIG_DIR;

beforeEach(() => {
  dir = mkdtempSync(join(tmpdir(), "overdeck-token-"));
  process.env.OVERDECK_CONFIG_DIR = dir;
});

afterEach(() => {
  rmSync(dir, { recursive: true, force: true });
  if (originalEnv === undefined) delete process.env.OVERDECK_CONFIG_DIR;
  else process.env.OVERDECK_CONFIG_DIR = originalEnv;
});

describe("token generation", () => {
  test("generates a token file with mode 600 when missing", () => {
    const token = loadOrCreateToken();
    expect(token).toMatch(/^[a-f0-9]{64}$/);

    const stat = statSync(join(dir, "token"));
    expect(stat.mode & 0o777).toBe(0o600);
  });

  test("reuses an existing token on subsequent loads", () => {
    const first = loadOrCreateToken();
    const second = loadOrCreateToken();
    expect(second).toBe(first);
  });

  test("token file contents match what is returned", () => {
    const token = loadOrCreateToken();
    const onDisk = readFileSync(join(dir, "token"), "utf8").trim();
    expect(onDisk).toBe(token);
  });
});
