import { describe, it, expect } from "vitest";
import { join, resolve } from "node:path";
import { homedir } from "node:os";
import {
  DEFAULT_ZENCODE_CODEX_HOME,
  getLegacyCodexHome,
  resolveZencodeCodexHome,
  resolveZencodeCodexSessionHome,
} from "./codex-home.js";

describe("codex-home", () => {
  it("DEFAULT_ZENCODE_CODEX_HOME points to ~/.zencode/codex-home", () => {
    expect(DEFAULT_ZENCODE_CODEX_HOME).toBe(
      join(homedir(), ".zencode", "codex-home"),
    );
  });

  it("getLegacyCodexHome returns ~/.codex", () => {
    expect(getLegacyCodexHome()).toBe(join(homedir(), ".codex"));
  });

  it("resolveZencodeCodexHome returns default when no explicit path given", () => {
    expect(resolveZencodeCodexHome()).toBe(DEFAULT_ZENCODE_CODEX_HOME);
  });

  it("resolveZencodeCodexHome uses explicit path when provided", () => {
    const custom = "/tmp/my-codex-home";
    expect(resolveZencodeCodexHome(custom)).toBe(resolve(custom));
  });

  // Regression: resolveZencodeCodexHome must NOT read process.env.CODEX_HOME
  // because that points to the user's global ~/.codex and would break per-session isolation.
  it("resolveZencodeCodexHome ignores process.env.CODEX_HOME", () => {
    const original = process.env.CODEX_HOME;
    try {
      process.env.CODEX_HOME = "/tmp/global-codex";
      expect(resolveZencodeCodexHome()).toBe(DEFAULT_ZENCODE_CODEX_HOME);
    } finally {
      if (original === undefined) {
        delete process.env.CODEX_HOME;
      } else {
        process.env.CODEX_HOME = original;
      }
    }
  });

  it("resolveZencodeCodexSessionHome appends sessionId to base", () => {
    const sessionId = "abc-123";
    expect(resolveZencodeCodexSessionHome(sessionId)).toBe(
      join(DEFAULT_ZENCODE_CODEX_HOME, sessionId),
    );
  });

  it("resolveZencodeCodexSessionHome uses explicit path", () => {
    const custom = "/tmp/my-codex-home";
    const sessionId = "xyz-789";
    expect(resolveZencodeCodexSessionHome(sessionId, custom)).toBe(
      join(resolve(custom), sessionId),
    );
  });
});
