import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { randomBytes, createHash } from 'crypto'

// GET /api/keys — list user's API keys
export async function GET() {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const keys = await prisma.apiKey.findMany({
    where: { userId: session.user.id },
    orderBy: { createdAt: 'desc' },
    select: {
      id: true,
      name: true,
      key: true,
      active: true,
      createdAt: true,
    },
  })

  // Mask keys — only show prefix + last 4 chars
  const masked = keys.map((k) => ({
    ...k,
    key: k.key.slice(0, 8) + '••••••••' + k.key.slice(-4),
  }))

  return NextResponse.json({ keys: masked })
}

// POST /api/keys — create a new API key
export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const body = await req.json()
  const name = body.name?.trim()

  if (!name || name.length < 2) {
    return NextResponse.json(
      { error: 'Nome da chave é obrigatório (mínimo 2 caracteres)' },
      { status: 400 }
    )
  }

  // Check key limit (max 5)
  const count = await prisma.apiKey.count({
    where: { userId: session.user.id },
  })

  if (count >= 5) {
    return NextResponse.json(
      { error: 'Limite de 5 chaves atingido. Revogue uma chave existente.' },
      { status: 400 }
    )
  }

  // Generate key: jur_ prefix + 40 random hex chars
  const rawKey = 'jur_' + randomBytes(20).toString('hex')
  const hashedKey = createHash('sha256').update(rawKey).digest('hex')

  const apiKey = await prisma.apiKey.create({
    data: {
      name,
      key: hashedKey,
      userId: session.user.id,
    },
    select: {
      id: true,
      name: true,
      createdAt: true,
    },
  })

  // Return the raw key ONLY on creation (never stored/shown again)
  return NextResponse.json({
    ...apiKey,
    key: rawKey,
    message: 'Copie a chave agora. Ela não será exibida novamente.',
  }, { status: 201 })
}
