/**
 * Rotas de Figurinhas (Stickers)
 *
 * GET   /api/stickers            — Lista stickers do tenant (com listVersion)
 * GET   /api/stickers/recent     — Últimos 30 stickers usados
 * PATCH /api/stickers/:id/favorite — Toggle isFavorite
 */
import { Router, type Request, type Response } from 'express'
import { createHash } from 'crypto'
import { prisma } from '../../infra/database/prisma'

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

  // ── LIST (com listVersion para cache invalidation) ────────────────────────
  router.get('/', async (req: Request, res: Response) => {
    try {
      const tenantId = req.tenantId!

      const stickers = await prisma.sticker.findMany({
        where: { tenantId },
        orderBy: [{ isFavorite: 'desc' }, { lastSeenAt: 'desc' }],
        select: {
          id:         true,
          sha256:     true,
          wasabiPath: true,
          isAnimated: true,
          isFavorite: true,
          useCount:   true,
          lastSeenAt: true,
        },
      })

      const versionSource = stickers.length === 0
        ? 'empty'
        : `${stickers.length}:${stickers[0]!.sha256}:${stickers[0]!.lastSeenAt.getTime()}:${stickers.filter(s => s.isFavorite).length}`
      const listVersion = createHash('md5').update(versionSource).digest('hex').slice(0, 8)

      res.json({ listVersion, stickers })
    } catch (err) {
      res.status(500).json({ error: 'Erro ao listar stickers' })
    }
  })

  // ── RECENT (últimos 30) ───────────────────────────────────────────────────
  router.get('/recent', async (req: Request, res: Response) => {
    try {
      const tenantId = req.tenantId!

      const stickers = await prisma.sticker.findMany({
        where: { tenantId },
        orderBy: { lastSeenAt: 'desc' },
        take: 30,
        select: {
          id:         true,
          sha256:     true,
          wasabiPath: true,
          isAnimated: true,
          isFavorite: true,
        },
      })

      res.json({ stickers })
    } catch (err) {
      res.status(500).json({ error: 'Erro ao listar stickers recentes' })
    }
  })

  // ── TOGGLE FAVORITE ───────────────────────────────────────────────────────
  router.patch('/:id/favorite', async (req: Request, res: Response) => {
    try {
      const tenantId = req.tenantId!
      const idParam = req.params['id']
      const id = Array.isArray(idParam) ? idParam[0]! : idParam

      const sticker = await prisma.sticker.findFirst({
        where: { id, tenantId },
        select: { id: true, isFavorite: true },
      })

      if (!sticker) {
        res.status(404).json({ error: 'Sticker não encontrado' })
        return
      }

      const updated = await prisma.sticker.update({
        where: { id: sticker.id },
        data:  { isFavorite: !sticker.isFavorite },
        select: { id: true, isFavorite: true },
      })

      res.json(updated)
    } catch (err) {
      res.status(500).json({ error: 'Erro ao atualizar favorito' })
    }
  })

  return router
}
