/**
 * Rotas de Templates de Mensagem
 *
 * GET    /api/templates            — Lista templates do tenant
 * POST   /api/templates            — Cria template
 * GET    /api/templates/:id        — Detalhe do template
 * PUT    /api/templates/:id        — Atualiza template
 * DELETE /api/templates/:id        — Remove template
 * POST   /api/templates/:id/use    — Incrementa usageCount (IA chama ao usar)
 */
import { Router, type Request, type Response } from 'express'
import { z } from 'zod'
import { prisma } from '../../infra/database/prisma'

const templateTypeValues = ['TEXT', 'BUTTONS', 'INTERACTIVE', 'LIST', 'POLL', 'CAROUSEL'] as const

const templateSchema = z.object({
  name:        z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  type:        z.enum(templateTypeValues),
  payload:     z.record(z.unknown()),
  tags:        z.array(z.string()).default([]),
})

function getId(req: Request): string {
  const id = req.params['id']
  return Array.isArray(id) ? id[0] : id
}

export function buildTemplateRoutes(): Router {
  const router = Router()

  // ── LIST ──────────────────────────────────────────────────────────────────
  router.get('/', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const type   = Array.isArray(req.query['type'])   ? req.query['type'][0]   : req.query['type']
    const search = Array.isArray(req.query['search']) ? req.query['search'][0] : req.query['search']

    const templates = await prisma.messageTemplate.findMany({
      where: {
        tenantId,
        ...(type   ? { type: type as any } : {}),
        ...(search ? { name: { contains: search as string, mode: 'insensitive' } } : {}),
      },
      orderBy: [{ usageCount: 'desc' }, { createdAt: 'desc' }],
    })

    res.json(templates)
  })

  // ── CREATE ────────────────────────────────────────────────────────────────
  router.post('/', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const parse = templateSchema.safeParse(req.body)
    if (!parse.success) {
      res.status(400).json({ error: parse.error.errors })
      return
    }

    const { name, description, type, payload, tags } = parse.data

    const template = await prisma.messageTemplate.create({
      data: { tenantId, name, description, type, payload: payload as any, tags },
    })

    res.status(201).json(template)
  })

  // ── GET ONE ───────────────────────────────────────────────────────────────
  router.get('/:id', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const template = await prisma.messageTemplate.findFirst({
      where: { id: getId(req), tenantId },
    })
    if (!template) { res.status(404).json({ error: 'Template não encontrado' }); return }
    res.json(template)
  })

  // ── UPDATE ────────────────────────────────────────────────────────────────
  router.put('/:id', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const id = getId(req)
    const exists = await prisma.messageTemplate.findFirst({
      where: { id, tenantId },
    })
    if (!exists) { res.status(404).json({ error: 'Template não encontrado' }); return }

    const parse = templateSchema.partial().safeParse(req.body)
    if (!parse.success) {
      res.status(400).json({ error: parse.error.errors })
      return
    }

    const { payload, ...rest } = parse.data
    const updated = await prisma.messageTemplate.update({
      where: { id },
      data: { ...rest, ...(payload !== undefined ? { payload: payload as any } : {}) },
    })

    res.json(updated)
  })

  // ── DELETE ────────────────────────────────────────────────────────────────
  router.delete('/:id', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const id = getId(req)
    const exists = await prisma.messageTemplate.findFirst({
      where: { id, tenantId },
    })
    if (!exists) { res.status(404).json({ error: 'Template não encontrado' }); return }

    await prisma.messageTemplate.delete({ where: { id } })
    res.status(204).send()
  })

  // ── USE (IA incrementa uso) ────────────────────────────────────────────────
  router.post('/:id/use', async (req: Request, res: Response) => {
    const tenantId = req.tenantId!
    const id = getId(req)
    const exists = await prisma.messageTemplate.findFirst({
      where: { id, tenantId },
    })
    if (!exists) { res.status(404).json({ error: 'Template não encontrado' }); return }

    await prisma.messageTemplate.update({
      where: { id },
      data: { usageCount: { increment: 1 } },
    })

    res.json({ ok: true })
  })

  return router
}
