import { NextRequest, NextResponse } from 'next/server'

export async function POST(request: NextRequest) {
  try {
    const { code, state } = await request.json()

    if (!code) {
      return NextResponse.json(
        { error: 'Authorization code is required' },
        { status: 400 }
      )
    }

    // Validate state for CSRF protection
    const storedState = request.cookies.get('qwen_auth_state')?.value
    if (state && storedState !== state) {
      return NextResponse.json(
        { error: 'Invalid state parameter' },
        { status: 400 }
      )
    }

    // In production, exchange code for actual Qwen token
    // For demo, create a mock token
    const mockAccessToken = `qwen_token_${code}_${Date.now()}`
    const mockRefreshToken = `qwen_refresh_${code}_${Date.now()}`
    const mockExpiresIn = 3600 // 1 hour

    // Store in cookie for server-side access
    const response = NextResponse.json({
      access_token: mockAccessToken,
      refresh_token: mockRefreshToken,
      expires_in: mockExpiresIn,
      token_type: 'Bearer',
      success: true,
      redirect_to: '/',
    })

    // Set secure HTTP-only cookie
    response.cookies.set('qwen_access_token', mockAccessToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: mockExpiresIn,
      path: '/',
    })

    // Clear state cookie
    response.cookies.set('qwen_auth_state', '', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 0,
      path: '/',
    })

    return response

  } catch (error) {
    console.error('Qwen auth callback error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}