import { NextRequest, NextResponse } from 'next/server'
import { getCurrentUser } from '@/lib/auth'
import { getCharacterInventory } from '@/lib/services/inventory-service'
import { getInventoryAdapter } from '@/lib/services/inventory-adapters'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const currentUser = await getCurrentUser()
    if (!currentUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: characterId } = await params

    if (!characterId) {
      return NextResponse.json({ error: 'Character ID required' }, { status: 400 })
    }

    console.log('[Inventory API] Fetching inventory for character:', characterId)

    // Try to get the inventory adapter
    try {
      const adapter = await getInventoryAdapter()
      const inventory = await adapter.getCharacterInventory(characterId)
      
      console.log('[Inventory API] Inventory loaded via adapter:', {
        itemCount: inventory.items.length,
        type: inventory.inventoryType
      })

      return NextResponse.json({
        success: true,
        inventory: {
          items: inventory.items,
          maxWeight: inventory.maxWeight,
          currentWeight: inventory.currentWeight,
          maxSlots: inventory.maxSlots,
          usedSlots: inventory.usedSlots,
        }
      })
    } catch (adapterError) {
      console.log('[Inventory API] Adapter failed, trying direct service:', adapterError)
      
      // Fallback to direct inventory service
      const inventory = await getCharacterInventory(characterId)
      
      console.log('[Inventory API] Direct service result:', {
        itemCount: inventory.items.length
      })

      return NextResponse.json({
        success: true,
        inventory: {
          items: inventory.items,
          maxWeight: inventory.maxWeight || 120000,
          currentWeight: inventory.currentWeight || 0,
          maxSlots: inventory.maxSlots || 41,
          usedSlots: inventory.items.length,
        }
      })
    }
  } catch (error) {
    console.error('[Inventory API] Error:', error)
    return NextResponse.json(
      { 
        error: 'Failed to load inventory',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}
