import { NextRequest, NextResponse } from 'next/server'
import prisma from './prisma'

export interface H2HUser {
  id: string
  name: string
  email: string
  balance: number
  role: string
  apiKeyId: string
}

const rateLimitMap = new Map<string, { count: number, resetAt: number }>()

export async function authenticateH2H(req: NextRequest): Promise<H2HUser | null> {
  const apiKey = req.headers.get('x-api-key') || req.headers.get('authorization')?.replace('Bearer ', '') || req.nextUrl.searchParams.get('api_key')

  if (!apiKey) return null

  const keyRecord = await prisma.apiKey.findUnique({
    where: { key: apiKey, isActive: true },
    include: {
      user: {
        select: { id: true, name: true, email: true, balance: true, role: true, isBanned: true },
      },
    },
  })

  if (!keyRecord || !keyRecord.user) return null
  if (keyRecord.user.isBanned) return null

  // Rate Limiting (In-Memory per minute)
  const now = Date.now()
  const rl = rateLimitMap.get(apiKey)
  const limit = keyRecord.user.role === 'USER' ? 30 : 120 // 30 req/min for USER, 120 for RESELLER/ADMIN
  if (rl && rl.resetAt > now) {
    if (rl.count >= limit) {
      console.warn(`[H2H] Rate limit exceeded for key ${keyRecord.id} (Role: ${keyRecord.user.role})`)
      return null
    }
    rl.count++
  } else {
    rateLimitMap.set(apiKey, { count: 1, resetAt: now + 60000 })
  }

  // IP Whitelist check
  if (keyRecord.ipWhitelist) {
    try {
      const allowedIPs: string[] = JSON.parse(keyRecord.ipWhitelist)
      if (allowedIPs.length > 0) {
        const clientIP =
          req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
          req.headers.get('x-real-ip') ||
          '0.0.0.0'
        if (!allowedIPs.includes(clientIP)) {
          console.warn(`[H2H] IP blocked: ${clientIP} not in whitelist for key ${keyRecord.id}`)
          return null
        }
      }
    } catch {
      // Invalid JSON in whitelist, skip check
    }
  }

  // Update last used
  await prisma.apiKey.update({
    where: { id: keyRecord.id },
    data: { lastUsedAt: new Date() },
  }).catch(() => {})

  return {
    id: keyRecord.user.id,
    name: keyRecord.user.name,
    email: keyRecord.user.email,
    balance: Number(keyRecord.user.balance),
    role: keyRecord.user.role,
    apiKeyId: keyRecord.id,
  }
}

export function h2hUnauthorized(message = 'API Key tidak valid atau tidak aktif') {
  return NextResponse.json({ success: false, error: message }, { status: 401 })
}

export function generateApiKey(): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const part1 = Array.from({ length: 8 }, () => chars[Math.floor(Math.random() * chars.length)]).join('')
  const part2 = Array.from({ length: 16 }, () => chars[Math.floor(Math.random() * chars.length)]).join('')
  const part3 = Array.from({ length: 8 }, () => chars[Math.floor(Math.random() * chars.length)]).join('')
  return `ANK-${part1}-${part2}-${part3}`
}
