import { NextResponse } from 'next/server'
import jwt from 'jsonwebtoken'

export const runtime = 'nodejs'

export async function POST(request: Request) {
  try {
    const { token } = await request.json()

    if (!token) {
      return NextResponse.json({ error: 'Token required' }, { status: 400 })
    }

    // Log environment info
    const hasSecret = !!process.env.JWT_SECRET
    const secretPreview = process.env.JWT_SECRET ? process.env.JWT_SECRET.substring(0, 10) + '...' : 'MISSING'

    console.log('Debug: JWT_SECRET exists:', hasSecret)
    console.log('Debug: JWT_SECRET preview:', secretPreview)

    // Try to decode without verification first
    let decodedWithoutVerification
    try {
      decodedWithoutVerification = jwt.decode(token, { complete: true })
      console.log('Debug: Token decoded without verification:', !!decodedWithoutVerification)
    } catch (e) {
      console.log('Debug: Token decode failed:', e.message)
    }

    // Try to verify
    let verificationResult
    try {
      verificationResult = jwt.verify(token, process.env.JWT_SECRET!)
      console.log('Debug: Token verification successful')
    } catch (e) {
      console.log('Debug: Token verification failed:', e.message)
      verificationResult = { error: e.message }
    }

    return NextResponse.json({
      hasSecret,
      secretPreview,
      decodedWithoutVerification: !!decodedWithoutVerification,
      payload: decodedWithoutVerification?.payload,
      verificationResult: typeof verificationResult === 'object' && 'error' in verificationResult
        ? verificationResult
        : { success: true, payload: verificationResult }
    })
  } catch (error) {
    console.error('Debug endpoint error:', error)
    return NextResponse.json({ error: 'Debug failed' }, { status: 500 })
  }
}