import { proxyActivities } from "@temporalio/workflow";

import type { WorkbenchActivityConfig, WorkbenchTurnInput } from "./contracts.ts";

type WorkbenchActivities = {
  dispatchWorkbenchTurn(input: WorkbenchTurnInput): Promise<Record<string, unknown>>;
  cancelWorkbenchTurn(input: { actor: WorkbenchTurnInput["actor"]; traceId: string; params: Record<string, unknown> }): Promise<Record<string, unknown>>;
};

export async function workbenchTurnWorkflow(input: WorkbenchTurnInput & { activity: WorkbenchActivityConfig }) {
  const activities = workbenchActivities(input.activity);
  const dispatch = await activities.dispatchWorkbenchTurn(input);
  return { accepted: true, traceId: input.traceId, dispatch, terminalAuthority: "hwlab.event.v1", resultSynthesized: false };
}

export async function workbenchCancelWorkflow(input: { actor: WorkbenchTurnInput["actor"]; traceId: string; params: Record<string, unknown>; activity: WorkbenchActivityConfig }) {
  const activities = workbenchActivities(input.activity);
  const cancel = await activities.cancelWorkbenchTurn(input);
  return { accepted: true, traceId: input.traceId, cancel, terminalAuthority: "hwlab.event.v1", resultSynthesized: false };
}

function workbenchActivities(activity: WorkbenchActivityConfig) {
  return proxyActivities<WorkbenchActivities>({
    startToCloseTimeout: `${activity.startToCloseTimeoutMs} milliseconds`,
    retry: { initialInterval: `${activity.retryInitialIntervalMs} milliseconds`, maximumInterval: `${activity.retryMaximumIntervalMs} milliseconds`, maximumAttempts: activity.retryMaximumAttempts }
  });
}
