/**
 * Preview Router — start, stop, list, status for Docker-based preview deployments
 */

import { z } from 'zod';
import type { ProcedureBuilder } from '../trpc.js';
import { requirePreviewManager, requireAgentManager } from './_helpers.js';

export function previewProcedures(publicProcedure: ProcedureBuilder) {
  return {
    startPreview: publicProcedure
      .input(z.object({
        initiativeId: z.string().min(1),
        phaseId: z.string().min(1).optional(),
        projectId: z.string().min(1),
        branch: z.string().min(1),
        mode: z.enum(['preview', 'dev']).default('preview'),
        worktreePath: z.string().optional(),
        agentId: z.string().min(1).optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        return previewManager.start(input);
      }),

    startPreviewForAgent: publicProcedure
      .input(z.object({ agentId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        const agentManager = requireAgentManager(ctx);
        return previewManager.startForAgent(input.agentId, agentManager);
      }),

    stopPreviewByAgent: publicProcedure
      .input(z.object({ agentId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        await previewManager.stopByAgentId(input.agentId);
        return { success: true };
      }),

    stopPreview: publicProcedure
      .input(z.object({
        previewId: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        await previewManager.stop(input.previewId);
        return { success: true };
      }),

    listPreviews: publicProcedure
      .input(z.object({
        initiativeId: z.string().min(1).optional(),
      }).optional())
      .query(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        return previewManager.list(input?.initiativeId);
      }),

    getPreviewStatus: publicProcedure
      .input(z.object({
        previewId: z.string().min(1),
      }))
      .query(async ({ ctx, input }) => {
        const previewManager = requirePreviewManager(ctx);
        return previewManager.getStatus(input.previewId);
      }),
  };
}
