import { NextResponse } from 'next/server'

export async function POST(request) {
  try {
    console.log('🌊 Drift login attempt...')

    // Check if environment is configured
    if (!process.env.SOLANA_PRIVATE_KEY) {
      return NextResponse.json({
        success: false,
        isLoggedIn: false,
        error: 'Drift not configured - missing SOLANA_PRIVATE_KEY'
      }, { status: 400 })
    }

    // Import Drift SDK components (same as execute-drift route)
    const { DriftClient, initialize } = await import('@drift-labs/sdk')
    const { Connection, Keypair } = await import('@solana/web3.js')

    // Initialize connection and wallet
    const connection = new Connection(
      process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',
      'confirmed'
    )

    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
    
    // Create wallet interface manually since Anchor Wallet constructor is not working
    const wallet = {
      publicKey: keypair.publicKey,
      signTransaction: async (tx) => {
        tx.partialSign(keypair)
        return tx
      },
      signAllTransactions: async (txs) => {
        return txs.map(tx => {
          tx.partialSign(keypair)
          return tx
        })
      }
    }
    
    const publicKey = keypair.publicKey.toString()

    console.log('🔐 Connecting to Drift with wallet:', publicKey)

    // Initialize Drift SDK
    const env = 'mainnet-beta'
    const sdkConfig = initialize({ env })
    
    const driftClient = new DriftClient({
      connection,
      wallet,
      programID: sdkConfig.DRIFT_PROGRAM_ID,
      opts: {
        commitment: 'confirmed',
      },
    })

    try {
      // Subscribe to drift client
      await driftClient.subscribe()
      console.log('✅ Connected to Drift successfully')

      // Check if user account exists
      let userAccountExists = false
      let userAccountPublicKey = null
      
      try {
        const userAccountPubkey = await driftClient.getUserAccountPublicKey()
        userAccountPublicKey = userAccountPubkey.toString()
        
        // Try to fetch user account to see if it exists
        const userAccount = await driftClient.getUserAccount()
        userAccountExists = !!userAccount
        
        console.log('👤 User account status:', {
          exists: userAccountExists,
          publicKey: userAccountPublicKey
        })
        
      } catch (accountError) {
        console.log('ℹ️ User account not found or not initialized')
        userAccountExists = false
      }

      // Clean up connection
      await driftClient.unsubscribe()

      return NextResponse.json({
        success: true,
        isLoggedIn: true,
        publicKey: publicKey,
        userAccountExists: userAccountExists,
        userAccountPublicKey: userAccountPublicKey,
        driftProgramId: sdkConfig.DRIFT_PROGRAM_ID.toString(),
        connection: 'mainnet-beta',
        message: userAccountExists 
          ? '✅ Drift account ready for trading'
          : '⚠️ Drift account exists but may need initialization'
      })

    } catch (subscribeError) {
      console.error('❌ Failed to connect to Drift:', subscribeError)
      
      return NextResponse.json({
        success: false,
        isLoggedIn: false,
        error: 'Failed to connect to Drift Protocol',
        details: subscribeError.message,
        publicKey: publicKey
      }, { status: 400 })
    }

  } catch (error) {
    console.error('❌ Drift login error:', error)
    
    return NextResponse.json({
      success: false,
      isLoggedIn: false,
      error: 'Drift login failed',
      details: error.message
    }, { status: 500 })
  }
}

export async function GET() {
  return NextResponse.json({
    message: 'Drift Protocol Login API',
    endpoints: {
      'POST /api/drift/login': 'Initialize connection to Drift Protocol'
    },
    status: 'Active',
    requirements: [
      'SOLANA_PRIVATE_KEY environment variable',
      'Valid Solana wallet with USDC',
      'Internet connection to Solana mainnet'
    ]
  })
}
