import { z } from 'zod'
import type { Prisma } from '@prisma/client'
import { router, adminProcedure } from '../trpc'
import { wizardConfigSchema } from '@/types/wizard-config'
import { logAudit } from '../utils/audit'

export const wizardTemplateRouter = router({
  list: adminProcedure
    .input(z.object({ programId: z.string().optional() }).optional())
    .query(async ({ ctx, input }) => {
      return ctx.prisma.wizardTemplate.findMany({
        where: {
          OR: [
            { isGlobal: true },
            ...(input?.programId ? [{ programId: input.programId }] : []),
          ],
        },
        orderBy: { createdAt: 'desc' },
        include: { creator: { select: { name: true } } },
      })
    }),

  create: adminProcedure
    .input(
      z.object({
        name: z.string().min(1).max(100),
        description: z.string().max(500).optional(),
        config: wizardConfigSchema,
        isGlobal: z.boolean().default(false),
        programId: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const template = await ctx.prisma.wizardTemplate.create({
        data: {
          name: input.name,
          description: input.description,
          config: input.config as unknown as Prisma.InputJsonValue,
          isGlobal: input.isGlobal,
          programId: input.programId,
          createdBy: ctx.user.id,
        },
      })

      await logAudit({
        prisma: ctx.prisma,
        userId: ctx.user.id,
        action: 'CREATE',
        entityType: 'WizardTemplate',
        entityId: template.id,
        detailsJson: { name: input.name },
        ipAddress: ctx.ip,
        userAgent: ctx.userAgent,
      })

      return template
    }),

  delete: adminProcedure
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.prisma.wizardTemplate.delete({ where: { id: input.id } })

      await logAudit({
        prisma: ctx.prisma,
        userId: ctx.user.id,
        action: 'DELETE',
        entityType: 'WizardTemplate',
        entityId: input.id,
        ipAddress: ctx.ip,
        userAgent: ctx.userAgent,
      })

      return { success: true }
    }),
})
