import { describe, expect, it } from "vitest";
import { AddressCommitStateMachine } from "@/workers/rpa/address-adapter/commit-state-machine";
import { formatDiagnosticsFailure } from "@/workers/rpa/address-adapter/diagnostics";
import { getRpaAddressMode } from "@/lib/rpa/address-mode";

describe("AddressCommitStateMachine", () => {
  it("COMMITTED 可进入下游", () => {
    const sm = new AddressCommitStateMachine();
    sm.transition("COMMITTED");
    expect(sm.canProceedToCargo()).toBe(true);
    expect(() => sm.assertCommittedForDownstream("pickup")).not.toThrow();
  });

  it("FAILED 禁止进入 cargo", () => {
    const sm = new AddressCommitStateMachine();
    sm.transition("FAILED");
    expect(sm.canProceedToCargo()).toBe(false);
    expect(() => sm.assertCommittedForDownstream("pickup")).toThrow(/COMMITTED/);
  });
});

describe("formatDiagnosticsFailure", () => {
  it("区分 no_place_request", () => {
    const msg = formatDiagnosticsFailure({
      address: "123 Main",
      placeId: "ChIJ_x",
      method: "keyboard",
      events: [],
      placeRequestObserved: false,
      status: "no_place_request",
      commitState: "FAILED",
    });
    expect(msg).toContain("未发起 GET place 请求");
    expect(msg).toContain("selection event");
  });
});

describe("getRpaAddressMode", () => {
  it("默认 real", () => {
    const prev = process.env.RPA_ADDRESS_MODE;
    delete process.env.RPA_ADDRESS_MODE;
    expect(getRpaAddressMode()).toBe("real");
    process.env.RPA_ADDRESS_MODE = prev;
  });

  it("mock 显式启用", () => {
    const prev = process.env.RPA_ADDRESS_MODE;
    process.env.RPA_ADDRESS_MODE = "mock";
    expect(getRpaAddressMode()).toBe("mock");
    process.env.RPA_ADDRESS_MODE = prev;
  });
});
