import fs from "node:fs";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { resolveStorageStatePath } from "@/lib/axel/session";
import { runWithMothershipLoginContext } from "@/lib/rpa/mothership-login-context";

const TMP = path.join(process.cwd(), ".rpa", "_tmp-logged-in-storage-test.json");

describe("resolveStorageStatePath 登录态优先", () => {
  afterEach(() => {
    if (fs.existsSync(TMP)) fs.unlinkSync(TMP);
    delete process.env.RPA_LOGGED_IN_STORAGE_STATE_PATH;
  });

  it("有登录凭据且 logged-in storage 存在时使用登录态路径", async () => {
    process.env.RPA_LOGGED_IN_STORAGE_STATE_PATH = TMP;
    fs.mkdirSync(path.dirname(TMP), { recursive: true });
    fs.writeFileSync(TMP, JSON.stringify({ cookies: [], origins: [] }), "utf8");

    await runWithMothershipLoginContext(
      { email: "a@b.com", password: "x" },
      "customer",
      async () => {
        expect(resolveStorageStatePath()).toBe(TMP);
      },
    );
  });
});
