/**
 * Dispatch Router — queue, dispatchNext, getQueueState, completeTask
 */

import { z } from 'zod';
import type { ProcedureBuilder } from '../trpc.js';
import { requireDispatchManager } from './_helpers.js';

export function dispatchProcedures(publicProcedure: ProcedureBuilder) {
  return {
    queueTask: publicProcedure
      .input(z.object({ taskId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const dispatchManager = requireDispatchManager(ctx);
        await dispatchManager.queue(input.taskId);
        return { success: true };
      }),

    dispatchNext: publicProcedure
      .mutation(async ({ ctx }) => {
        const dispatchManager = requireDispatchManager(ctx);
        return dispatchManager.dispatchNext();
      }),

    getQueueState: publicProcedure
      .query(async ({ ctx }) => {
        const dispatchManager = requireDispatchManager(ctx);
        return dispatchManager.getQueueState();
      }),

    completeTask: publicProcedure
      .input(z.object({ taskId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const dispatchManager = requireDispatchManager(ctx);
        await dispatchManager.completeTask(input.taskId);
        return { success: true };
      }),

    retryBlockedTask: publicProcedure
      .input(z.object({ taskId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const dispatchManager = requireDispatchManager(ctx);
        await dispatchManager.retryBlockedTask(input.taskId);
        // Kick dispatch loop to pick up the re-queued task
        await dispatchManager.dispatchNext();
        return { success: true };
      }),
  };
}
