import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { generateApiKey } from '@/lib/h2h-auth'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

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

    return NextResponse.json({ keys })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal memuat API keys' }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await req.json().catch(() => ({}))
    const name = body.name || 'Default Key'

    // Limit based on role
    const limit = ['RESELLER', 'ADMIN'].includes(session.user.role as string) ? 3 : 1
    const count = await prisma.apiKey.count({ where: { userId: session.user.id } })
    if (count >= limit) {
      return NextResponse.json({ error: `Maksimal ${limit} API Key per akun untuk role Anda` }, { status: 400 })
    }

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

    return NextResponse.json({ apiKey })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal membuat API key' }, { status: 500 })
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { searchParams } = new URL(req.url)
    const keyId = searchParams.get('id')
    if (!keyId) return NextResponse.json({ error: 'ID diperlukan' }, { status: 400 })

    await prisma.apiKey.deleteMany({
      where: { id: keyId, userId: session.user.id },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal hapus API key' }, { status: 500 })
  }
}

// PATCH: Update IP whitelist for an API Key (max 3 IPs)
export async function PATCH(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await req.json()
    const { keyId, ipWhitelist, webhookUrl } = body

    if (!keyId) return NextResponse.json({ error: 'keyId diperlukan' }, { status: 400 })

    const updateData: any = {}

    // Update IP Whitelist
    if (ipWhitelist !== undefined) {
      if (!Array.isArray(ipWhitelist)) {
        return NextResponse.json({ error: 'ipWhitelist harus berupa array' }, { status: 400 })
      }
      if (ipWhitelist.length > 3) {
        return NextResponse.json({ error: 'Maksimal 3 IP per API Key' }, { status: 400 })
      }
      const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/
      for (const ip of ipWhitelist) {
        if (ip && !ipRegex.test(ip)) {
          return NextResponse.json({ error: `IP tidak valid: ${ip}` }, { status: 400 })
        }
      }
      const filteredIPs = ipWhitelist.filter((ip: string) => ip && ip.trim())
      updateData.ipWhitelist = filteredIPs.length > 0 ? JSON.stringify(filteredIPs) : null
    }

    // Update Webhook URL
    if (webhookUrl !== undefined) {
      if (webhookUrl && !webhookUrl.startsWith('http')) {
        return NextResponse.json({ error: 'Webhook URL harus diawali http:// atau https://' }, { status: 400 })
      }
      updateData.webhookUrl = webhookUrl ? webhookUrl.trim() : null
    }

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json({ error: 'Tidak ada data untuk diupdate' }, { status: 400 })
    }

    await prisma.apiKey.updateMany({
      where: { id: keyId, userId: session.user.id },
      data: updateData,
    })

    return NextResponse.json({ success: true, ...updateData })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal update whitelist' }, { status: 500 })
  }
}
