import { RpaError } from "@/modules/rpa/errors";
import type { AddressCommitState } from "@/workers/rpa/address-adapter/types";

const TERMINAL: AddressCommitState[] = ["COMMITTED", "FAILED"];

export class AddressCommitStateMachine {
  private state: AddressCommitState = "EMPTY";

  getState(): AddressCommitState {
    return this.state;
  }

  transition(next: AddressCommitState): void {
    this.state = next;
  }

  isCommitted(): boolean {
    return this.state === "COMMITTED";
  }

  isFailed(): boolean {
    return this.state === "FAILED";
  }

  /** 禁止 FAILED / 未 COMMITTED 进入 cargo / submit / quote */
  assertCommittedForDownstream(side: "pickup" | "delivery"): void {
    if (this.state === "COMMITTED") {
      return;
    }
    const label = side === "pickup" ? "提货" : "派送";
    throw new RpaError(
      "ADDRESS_NOT_CONFIRMED",
      `${label}地址 commit 状态=${this.state}，禁止进入货物/提交/询价（须 COMMITTED）`,
      { retryable: this.state !== "FAILED" },
    );
  }

  canProceedToCargo(): boolean {
    return this.state === "COMMITTED";
  }

  isTerminal(): boolean {
    return TERMINAL.includes(this.state);
  }
}
