import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { generateShortCode } from '@/lib/utils/shortcode'

// 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: Generate code
    debugInfo.step = 'generate-code'
    const shortCode = generateShortCode(6)
    debugInfo.data.code = shortCode

    // Step 3: Create shortlink
    debugInfo.step = 'create-shortlink'
    const shortLink = await prisma.shortLink.create({
      data: {
        code: shortCode,
        link: body.link || 'https://example.com',
      },
    })
    debugInfo.data.shortlink = {
      id: shortLink.id.toString(),
      code: shortLink.code,
      link: shortLink.link,
      createdAt: shortLink.createdAt,
    }

    debugInfo.step = 'success'
    return NextResponse.json({
      success: true,
      debug: debugInfo,
      data: debugInfo.data.shortlink,
    })

  } 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 SHORTLINK ERROR ===')
    console.error('Step:', debugInfo.step)
    console.error('Error:', debugInfo.error)
    console.error('==============================')

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