import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";

describe("storage-state", () => {
  let tmpDir: string;

  afterEach(() => {
    if (tmpDir && fs.existsSync(tmpDir)) {
      fs.rmSync(tmpDir, { recursive: true, force: true });
    }
    vi.resetModules();
  });

  it("invalidateStorageState 删除 state 文件", async () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "rpa-state-"));
    const stateFile = path.join(tmpDir, "state.json");
    fs.writeFileSync(stateFile, "{}");
    process.env.RPA_STORAGE_STATE_PATH = stateFile;

    const { invalidateStorageState, storageStateExists } = await import(
      "@/lib/rpa/storage-state"
    );
    expect(storageStateExists()).toBe(true);
    invalidateStorageState();
    expect(storageStateExists()).toBe(false);
  });

  it("getStorageStateForContext 存在时返回 storageState", async () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "rpa-state-"));
    const stateFile = path.join(tmpDir, "state.json");
    fs.writeFileSync(stateFile, '{"cookies":[]}');
    process.env.RPA_STORAGE_STATE_PATH = stateFile;

    const { getStorageStateForContext } = await import(
      "@/lib/rpa/storage-state"
    );
    expect(getStorageStateForContext()).toEqual({ storageState: stateFile });
  });
});
