import { NextRequest, NextResponse } from 'next/server'
import { sanitizeApiKey } from '@/utils/api-utils'

export async function GET(request: NextRequest) {
  try {
    const authHeader = request.headers.get('authorization')
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: 'Authorization header is required' },
        { status: 401 }
      )
    }

    const token = authHeader.substring(7)

    // In a real implementation, you would verify the token with Qwen's API
    // For now, we'll just check if it exists and is not expired
    if (!token || token.startsWith('mock_')) {
      // For demo purposes, accept mock tokens
      // In production, you would validate this with Qwen's token endpoint
      return NextResponse.json({ 
        valid: true,
        message: 'Token is valid (demo mode)'
      })
    }

    // In production, you would call Qwen's token validation endpoint:
    /*
    const validationResponse = await fetch('https://open.bigmodel.cn/api/paas/v4/oauth2/validate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${sanitizeApiKey(token) || token}`,
        'Content-Type': 'application/json',
      },
    })

    if (!validationResponse.ok) {
      return NextResponse.json(
        { error: 'Token is invalid or expired' },
        { status: 401 }
      )
    }
    */

    return NextResponse.json({ 
      valid: true,
      message: 'Token is valid'
    })

  } catch (error) {
    console.error('Token verification error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}