import { workflowNames } from './workflow-names.js';

export type ProcessVoiceExperienceInput = {
  experienceId: string;
};

type HatchetClientLike = {
  run: (workflowName: string, input: Record<string, unknown>) => Promise<unknown>;
  runNoWait?: (workflowName: string, input: Record<string, unknown>) => Promise<unknown>;
};

let hatchet: HatchetClientLike | null = null;
let initDone = false;

async function ensureHatchetClient(): Promise<HatchetClientLike | null> {
  if (initDone) return hatchet;
  initDone = true;

  if (!process.env.HATCHET_CLIENT_TOKEN) {
    console.warn('[hatchet] HATCHET_CLIENT_TOKEN is not set, workflow trigger skipped');
    return null;
  }

  const sdk = await import('@hatchet-dev/typescript-sdk');
  hatchet = sdk.HatchetClient.init() as unknown as HatchetClientLike;
  return hatchet;
}

export async function enqueueVoiceExperience(
  input: ProcessVoiceExperienceInput,
) {
  const client = await ensureHatchetClient();
  if (!client) return { triggered: false };

  const runRef = client.runNoWait
    ? await client.runNoWait(workflowNames.processVoiceExperience, input)
    : await client.run(workflowNames.processVoiceExperience, input);

  return { triggered: true, runRef };
}
