import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";

import { resolveChatProfileDir } from "../src/profile-dir.js";

async function withTempDir(fn) {
  const root = await mkdtemp(path.join(os.tmpdir(), "chat-profile-dir-"));
  try {
    return await fn(root);
  } finally {
    await rm(root, { recursive: true, force: true });
  }
}

test("显式 CHAT_1688_PROFILE_DIR 优先于外置账号 profile", async () => {
  await withTempDir(async (root) => {
    const explicitDir = path.join(root, "explicit-profile");

    assert.equal(
      resolveChatProfileDir({
        env: { CHAT_1688_PROFILE_DIR: explicitDir },
        cwd: root,
        homeDir: root,
      }),
      explicitDir,
    );
  });
});

test("没有显式 profile 时按 SEARCH_1688_ACCOUNT_ID 使用外置长期账号 profile", async () => {
  await withTempDir(async (root) => {
    assert.equal(
      resolveChatProfileDir({
        env: { SEARCH_1688_ACCOUNT_ID: "account-2" },
        cwd: root,
        homeDir: root,
      }),
      path.join(root, ".1688-autoprocurement", "1688-profiles", "account-2"),
    );
  });
});

test("ALPHAPULSE_1688_PROFILE_ROOT 覆盖外置长期账号 profile 根目录", async () => {
  await withTempDir(async (root) => {
    assert.equal(
      resolveChatProfileDir({
        env: {
          ALPHAPULSE_1688_PROFILE_ROOT: "~/profiles",
          SEARCH_1688_ACCOUNT_ID: "account-3",
        },
        cwd: root,
        homeDir: root,
      }),
      path.join(root, "profiles", "account-3"),
    );
  });
});

test("没有 account id 时不再猜测项目内 legacy profile", async () => {
  await withTempDir(async (root) => {
    await mkdir(path.join(root, "automation", ".browser", "1688-profile"), { recursive: true });

    assert.equal(
      resolveChatProfileDir({
        env: {},
        cwd: root,
        homeDir: root,
      }),
      path.join(root, ".1688-autoprocurement", "1688-profiles", "__default_1688_account__"),
    );
  });
});
