/*
 * SPEC: PJ2026-010103 HWPOD 服务。
 * 实现引用: draft-2026-07-20-hwpod-temporal-split。
 * 责任: HWPOD API 到共享 Temporal namespace 的最小 gateway。
 */

import { Client, Connection } from "@temporalio/client";

export function createHwpodTemporalGateway(options: { address: string; namespace: string; taskQueue: string }) {
  if (!options.address) throw codedError("hwpod_temporal_address_required", "HWPOD_TEMPORAL_ADDRESS is required");
  let connection: Connection | undefined;
  let client: Client | undefined;
  const getClient = async () => {
    connection ??= await Connection.connect({ address: options.address });
    client ??= new Client({ connection, namespace: options.namespace });
    return client;
  };
  return {
    async start(input: unknown) {
      const workflowId = `hwpod-operation-${String((input as any)?.operationId ?? "unknown")}`;
      try {
        const handle = await (await getClient()).workflow.start("hwpodOperationWorkflow", { taskQueue: options.taskQueue, workflowId, args: [input] });
        return { workflowId, workflowRunId: handle.firstExecutionRunId, reused: false };
      } catch (error: any) {
        if (error?.name !== "WorkflowExecutionAlreadyStartedError") throw error;
        const description = await (await getClient()).workflow.getHandle(workflowId).describe();
        return { workflowId, workflowRunId: description.runId, reused: true };
      }
    },
    async describe(workflowId: string) { return (await getClient()).workflow.getHandle(workflowId).describe(); },
    async result(workflowId: string) { return (await getClient()).workflow.getHandle(workflowId).result(); },
    async close() { await connection?.close(); connection = undefined; client = undefined; }
  };
}

function codedError(code: string, message: string) { return Object.assign(new Error(message), { code }); }
