import { Router, type Request, type Response } from 'express'
import { z } from 'zod'
import { prisma } from '../../infra/database/prisma'
import crypto from 'crypto'

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

  // GET /api/api-keys
  router.get('/', async (req: Request, res: Response) => {
    const keys = await prisma.apiKey.findMany({
      where: { tenantId: req.tenantId! },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        name: true,
        key: true,
        isActive: true,
        createdAt: true,
        expiresAt: true,
      },
    })
    // Mask key: show only last 8 chars
    const masked = keys.map((k) => ({
      ...k,
      keyPreview: `••••••••${k.key.slice(-8)}`,
      key: undefined,
    }))
    res.json(masked)
  })

  // POST /api/api-keys — cria nova chave
  router.post('/', async (req: Request, res: Response) => {
    const schema = z.object({
      name:      z.string().min(1).max(80),
      expiresAt: z.string().datetime().optional(),
    })

    let body: z.infer<typeof schema>
    try { body = schema.parse(req.body) }
    catch (err: any) { res.status(400).json({ error: err.errors ?? err.message }); return }

    const key = `nw_${crypto.randomBytes(24).toString('hex')}`

    const created = await prisma.apiKey.create({
      data: {
        tenantId: req.tenantId!,
        name: body.name,
        key,
        expiresAt: body.expiresAt ? new Date(body.expiresAt) : undefined,
      },
    })

    // Retorna a chave completa apenas uma vez
    res.status(201).json({
      id: created.id,
      name: created.name,
      key: created.key,   // plaintext — única vez
      isActive: created.isActive,
      createdAt: created.createdAt,
      expiresAt: created.expiresAt,
    })
  })

  // PATCH /api/api-keys/:id — ativar/desativar
  router.patch('/:id', async (req: Request, res: Response) => {
    const id = req.params['id'] as string
    const schema = z.object({ isActive: z.boolean() })

    let body: z.infer<typeof schema>
    try { body = schema.parse(req.body) }
    catch (err: any) { res.status(400).json({ error: err.errors ?? err.message }); return }

    const existing = await prisma.apiKey.findFirst({ where: { id, tenantId: req.tenantId! } })
    if (!existing) { res.status(404).json({ error: 'Chave não encontrada' }); return }

    const updated = await prisma.apiKey.update({ where: { id }, data: { isActive: body.isActive } })
    res.json({ id: updated.id, name: updated.name, isActive: updated.isActive })
  })

  // DELETE /api/api-keys/:id
  router.delete('/:id', async (req: Request, res: Response) => {
    const id = req.params['id'] as string

    const existing = await prisma.apiKey.findFirst({ where: { id, tenantId: req.tenantId! } })
    if (!existing) { res.status(404).json({ error: 'Chave não encontrada' }); return }

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

  return router
}
