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 accountProfileRoot = path.join(root, "accounts");
    const explicitDir = path.join(root, "explicit-profile");
    await mkdir(path.join(accountProfileRoot, "account-1"), { recursive: true });

    assert.equal(
      resolveChatProfileDir({
        env: { CHAT_1688_PROFILE_DIR: explicitDir },
        cwd: root,
        accountProfileRoot,
        defaultProfileDir: path.join(root, "default"),
      }),
      explicitDir,
    );
  });
});

test("没有显式 profile 时按 SEARCH_1688_ACCOUNT_ID 复用自动化搜索账号 session", async () => {
  await withTempDir(async (root) => {
    const accountProfileRoot = path.join(root, "accounts");
    const expectedProfileDir = path.join(accountProfileRoot, "account-2");
    await mkdir(expectedProfileDir, { recursive: true });

    assert.equal(
      resolveChatProfileDir({
        env: { SEARCH_1688_ACCOUNT_ID: "account-2" },
        cwd: root,
        accountProfileRoot,
        defaultProfileDir: path.join(root, "default"),
      }),
      expectedProfileDir,
    );
  });
});

test("没有 account id 且仅有一个自动化账号 profile 时自动复用", async () => {
  await withTempDir(async (root) => {
    const accountProfileRoot = path.join(root, "accounts");
    const expectedProfileDir = path.join(accountProfileRoot, "only-account");
    await mkdir(expectedProfileDir, { recursive: true });

    assert.equal(
      resolveChatProfileDir({
        env: {},
        cwd: root,
        accountProfileRoot,
        defaultProfileDir: path.join(root, "default"),
      }),
      expectedProfileDir,
    );
  });
});

test("多个自动化账号 profile 且未指定 account id 时回退到 legacy automation profile", async () => {
  await withTempDir(async (root) => {
    const accountProfileRoot = path.join(root, "accounts");
    const legacyAutomationProfileDir = path.join(root, "legacy-profile");
    await mkdir(path.join(accountProfileRoot, "account-1"), { recursive: true });
    await mkdir(path.join(accountProfileRoot, "account-2"), { recursive: true });
    await mkdir(legacyAutomationProfileDir, { recursive: true });

    assert.equal(
      resolveChatProfileDir({
        env: {},
        cwd: root,
        accountProfileRoot,
        legacyAutomationProfileDir,
        defaultProfileDir: path.join(root, "default"),
      }),
      legacyAutomationProfileDir,
    );
  });
});
