import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { headers } from 'next/headers'
import crypto from 'crypto'

// TEMPORARY DEBUG ENDPOINT - HAPUS SETELAH DEBUG SELESAI!
export async function POST(request: NextRequest) {
  const debugInfo = {
    timestamp: new Date().toISOString(),
    step: 'start',
    error: null as any,
    data: {} as any,
  }

  try {
    // Step 1: Parse body
    debugInfo.step = 'parse-body'
    const body = await request.json()
    debugInfo.data.body = body

    // Step 2: Get headers
    debugInfo.step = 'get-headers'
    const headersList = await headers()
    debugInfo.data.headers = {
      userAgent: request.headers.get('user-agent'),
      referer: request.headers.get('referer'),
      xForwardedFor: headersList.get('x-forwarded-for'),
      xRealIP: headersList.get('x-real-ip'),
      cfConnectingIP: headersList.get('cf-connecting-ip'),
    }

    // Step 3: Get IP
    debugInfo.step = 'get-ip'
    const getClientIP = (): string => {
      const xForwardedFor = headersList.get('x-forwarded-for')
      const xRealIP = headersList.get('x-real-ip')
      const cfConnectingIP = headersList.get('cf-connecting-ip')

      if (xForwardedFor) return xForwardedFor.split(',')[0].trim()
      if (xRealIP) return xRealIP.trim()
      if (cfConnectingIP) return cfConnectingIP.trim()
      return 'unknown'
    }
    const ip = getClientIP()
    debugInfo.data.ip = ip

    // Step 4: Generate session ID
    debugInfo.step = 'generate-session'
    const userAgent = request.headers.get('user-agent') || ''
    const sessionData = `${ip}-${userAgent}-${new Date().toDateString()}`
    const sessionId = crypto.createHash('sha256').update(sessionData).digest('hex').substring(0, 32)
    debugInfo.data.sessionId = sessionId

    // Step 5: Check recent visit
    debugInfo.step = 'check-recent'
    const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000)
    const recentVisit = await prisma.visitor.findFirst({
      where: {
        ip,
        visitedAt: { gte: oneHourAgo }
      }
    })
    debugInfo.data.recentVisit = recentVisit ? 'found' : 'not-found'

    if (recentVisit) {
      debugInfo.step = 'skip-already-tracked'
      return NextResponse.json({
        success: true,
        message: 'Already tracked recently',
        debug: debugInfo,
      })
    }

    // Step 6: Create visitor record
    debugInfo.step = 'create-visitor'
    const visitor = await prisma.visitor.create({
      data: {
        ip,
        userAgent,
        path: body.path || '/',
        referrer: headersList.get('referer'),
        sessionId
      }
    })
    debugInfo.data.visitor = {
      id: visitor.id,
      ip: visitor.ip,
      path: visitor.path,
      visitedAt: visitor.visitedAt,
    }

    debugInfo.step = 'success'
    return NextResponse.json({
      success: true,
      message: 'Visitor tracked',
      debug: debugInfo,
      data: debugInfo.data.visitor,
    })

  } catch (error) {
    debugInfo.step = 'error'
    debugInfo.error = {
      message: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
      name: error instanceof Error ? error.name : undefined,
    }

    console.error('=== DEBUG VISITOR ERROR ===')
    console.error('Step:', debugInfo.step)
    console.error('Error:', debugInfo.error)
    console.error('===========================')

    return NextResponse.json({
      success: false,
      debug: debugInfo,
    }, { status: 500 })
  }
}
