import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { generateShortCode } from '@/lib/utils/shortcode'
import { getClientIP } from '@/lib/rate-limiter' // checkRateLimit temporarily disabled
import { isBlockedUrl, isValidUrlStrict } from '@/lib/url-blacklist'
// import { detectBot, extractRequestInfo, validateFormToken } from '@/lib/bot-detection' // Temporarily disabled
import { verifyRecaptcha } from '@/lib/recaptcha'

interface ShortLinkData {
  id: bigint
  code: string | null
  link: string | null
  createdAt: Date
  updatedAt: Date
  deletedAt: Date | null
}

// Helper to serialize BigInt to string for JSON
function serializeShortLink(link: ShortLinkData) {
  return {
    ...link,
    id: link.id.toString(),
  }
}

// GET all short links
export async function GET() {
  try {
    const links = await prisma.shortLink.findMany({
      where: {
        deletedAt: null,
      },
      orderBy: {
        createdAt: 'desc',
      },
    })

    // Serialize BigInt id to string
    const serializedLinks = links.map(serializeShortLink)

    return NextResponse.json({ success: true, data: serializedLinks })
  } catch (error) {
    console.error('=== SHORTLINK FETCH ERROR ===')
    console.error('Time:', new Date().toISOString())
    console.error('Error:', error)
    if (error instanceof Error) {
      console.error('Message:', error.message)
      console.error('Stack:', error.stack)
    }
    console.error('============================')
    return NextResponse.json(
      { success: false, error: 'Failed to fetch links' },
      { status: 500 }
    )
  }
}

// POST create new short link
export async function POST(request: NextRequest) {
  try {
    // === KEAMANAN 1: Rate Limiting ===
    // TEMPORARY DISABLED FOR DEBUGGING
    const clientIP = getClientIP(request)
    console.log('⚠️ Rate limiting DISABLED for debugging')
    /*
    const rateLimit = checkRateLimit(`shortlink:${clientIP}`, {
      maxRequests: 10,  // Maksimal 10 request
      windowMs: 60 * 1000,  // Per 1 menit
    })

    if (!rateLimit.success) {
      return NextResponse.json(
        {
          success: false,
          error: 'Terlalu banyak request. Silakan tunggu beberapa saat.'
        },
        {
          status: 429,
          headers: {
            'Retry-After': Math.ceil((rateLimit.resetTime - Date.now()) / 1000).toString(),
            'X-RateLimit-Remaining': '0',
          }
        }
      )
    }
    */

    const body = await request.json()
    const { link, code, _hp, _token, recaptchaToken } = body  // _hp = honeypot, _token = form token

    // === KEAMANAN 2: Google reCAPTCHA v3 ===
    const recaptchaResult = await verifyRecaptcha(recaptchaToken)
    if (!recaptchaResult.success) {
      console.log('reCAPTCHA failed:', {
        ip: clientIP,
        score: recaptchaResult.score,
        error: recaptchaResult.error,
      })
      return NextResponse.json(
        { success: false, error: recaptchaResult.error || 'Verifikasi reCAPTCHA gagal' },
        { status: 403 }
      )
    }

    // === KEAMANAN 3: Bot Detection (Honeypot + Timing) ===
    // TEMPORARY DISABLED FOR DEBUGGING
    /*
    const requestInfo = extractRequestInfo(request)

    // Validasi form token untuk hitung waktu submit
    let timeToSubmit: number | undefined
    if (_token) {
      const tokenValidation = validateFormToken(_token)
      if (tokenValidation.valid) {
        timeToSubmit = tokenValidation.timeToSubmit
      }
    }

    const botDetection = detectBot({
      ...requestInfo,
      honeypotValue: _hp,
      timeToSubmit,
    })

    if (botDetection.isBot) {
      console.log('Bot detected:', {
        ip: clientIP,
        score: botDetection.score,
        reasons: botDetection.reasons,
      })
      return NextResponse.json(
        { success: false, error: 'Request tidak valid' },
        { status: 403 }
      )
    }
    */

    // === KEAMANAN 4: Validasi URL Ketat ===
    if (!link || typeof link !== 'string') {
      return NextResponse.json(
        { success: false, error: 'URL wajib diisi' },
        { status: 400 }
      )
    }

    const urlValidation = isValidUrlStrict(link)
    if (!urlValidation.valid) {
      return NextResponse.json(
        { success: false, error: urlValidation.reason || 'URL tidak valid' },
        { status: 400 }
      )
    }

    // === KEAMANAN 5: Cek URL Blacklist ===
    const blockedCheck = isBlockedUrl(link)
    if (blockedCheck.blocked) {
      return NextResponse.json(
        { success: false, error: blockedCheck.reason || 'URL tidak diizinkan' },
        { status: 403 }
      )
    }

    let shortCode = code

    // Validate custom code if provided
    if (shortCode) {
      // Check if code exists and still active
      const existingLink = await prisma.shortLink.findFirst({
        where: { code: shortCode, deletedAt: null },
      })

      if (existingLink) {
        return NextResponse.json(
          { success: false, error: 'Code ini sudah dipakai. Silakan pilih code lain.' },
          { status: 400 }
        )
      }

      // Check if code is still active and within 60 days cooldown
      // Code can only be reused if: deleted OR created more than 60 days ago
      const sixtyDaysAgo = new Date()
      sixtyDaysAgo.setDate(sixtyDaysAgo.getDate() - 60)

      const activeRecentLink = await prisma.shortLink.findFirst({
        where: {
          code: shortCode,
          deletedAt: null,  // Still active (not deleted)
          createdAt: { gte: sixtyDaysAgo },  // Created within 60 days
        },
      })

      if (activeRecentLink) {
        const createdDate = new Date(activeRecentLink.createdAt)
        const availableDate = new Date(createdDate)
        availableDate.setDate(availableDate.getDate() + 60)
        const daysRemaining = Math.ceil((availableDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24))

        return NextResponse.json(
          { success: false, error: `Code ini baru bisa dipakai lagi dalam ${daysRemaining} hari.` },
          { status: 400 }
        )
      }

      // Check if code conflicts with existing microsite slug
      const existingMicrosite = await prisma.microsite.findUnique({
        where: { slug: shortCode },
      })

      if (existingMicrosite) {
        return NextResponse.json(
          { success: false, error: 'Code ini sudah dipakai oleh microsite' },
          { status: 400 }
        )
      }
    } else {
      // Generate unique random code
      let attempts = 0
      do {
        shortCode = generateShortCode(6)
        const existing = await prisma.shortLink.findFirst({
          where: { code: shortCode, deletedAt: null },
        })
        if (!existing) break
        attempts++
      } while (attempts < 10)

      if (attempts >= 10) {
        return NextResponse.json(
          { success: false, error: 'Failed to generate unique code' },
          { status: 500 }
        )
      }
    }

    // Create short link
    const shortLink = await prisma.shortLink.create({
      data: {
        code: shortCode!,
        link,
      },
    })

    return NextResponse.json(
      { success: true, data: serializeShortLink(shortLink) },
      {
        status: 201,
        // headers: {
        //   'X-RateLimit-Remaining': rateLimit.remaining.toString(),
        // }
      }
    )
  } catch (error) {
    console.error('=== SHORTLINK CREATION ERROR ===')
    console.error('Time:', new Date().toISOString())
    console.error('Error:', error)
    if (error instanceof Error) {
      console.error('Message:', error.message)
      console.error('Stack:', error.stack)
    }
    console.error('============================')
    return NextResponse.json(
      { success: false, error: 'Failed to create short link' },
      { status: 500 }
    )
  }
}
