import type { DeliveryDeploymentRecord, LandOperationRecord } from "./store";

export type DeliveryContinuationState = "landing" | "deployment-pending" | "deployment-observed" | "failed";

export interface DeliveryContinuation {
  operationId: string;
  state: DeliveryContinuationState;
  failure: string | null;
  nextAction: string | null;
  landedCommit: string | null;
  deploymentId: string | null;
  installedProof: "pending" | "passed";
}

export function projectDeliveryContinuation(
  operation: LandOperationRecord,
  deployment: DeliveryDeploymentRecord | null,
): DeliveryContinuation {
  if (operation.state === "waiting") {
    return {
      operationId: operation.operationId,
      state: "landing",
      failure: null,
      nextAction: "wait for guarded landing",
      landedCommit: null,
      deploymentId: null,
      installedProof: "pending",
    };
  }

  if (operation.state === "failed") {
    return {
      operationId: operation.operationId,
      state: "failed",
      failure: JSON.stringify(operation.verdict),
      nextAction: "inspect landing verdict",
      landedCommit: null,
      deploymentId: null,
      installedProof: "pending",
    };
  }

  if (deployment) {
    if (deployment.status === "ROLLED_BACK") {
      return {
        operationId: operation.operationId,
        state: "failed",
        failure: "deployment rolled back",
        nextAction: "inspect deployment evidence",
        landedCommit: operation.receipt.commit,
        deploymentId: deployment.deploymentId,
        installedProof: "pending",
      };
    }
    if (deployment.deployedSha !== operation.receipt.commit) {
      return {
        operationId: operation.operationId,
        state: "failed",
        failure: "deployment identity mismatch",
        nextAction: "inspect deployment evidence",
        landedCommit: operation.receipt.commit,
        deploymentId: deployment.deploymentId,
        installedProof: "pending",
      };
    }
    return {
      operationId: operation.operationId,
      state: "deployment-observed",
      failure: null,
      nextAction: "verify installed entrypoint",
      landedCommit: operation.receipt.commit,
      deploymentId: deployment.deploymentId,
      installedProof: "pending",
    };
  }

  return {
    operationId: operation.operationId,
    state: "deployment-pending",
    failure: null,
    nextAction: operation.receipt.nextAction,
    landedCommit: operation.receipt.commit,
    deploymentId: null,
    installedProof: "pending",
  };
}
