import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { getGameDbConfig, getGameDbPool } from '@/lib/game-db'
import { prisma } from '@/lib/db'

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getSession()
    
    if (!session || !['ADMIN', 'SUPERADMIN'].includes(session.role)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id } = await params
    const config = await getGameDbConfig()
    
    if (!config) {
      return NextResponse.json({ error: 'Game database not configured' }, { status: 500 })
    }

    const pool = await getGameDbPool()
    if (!pool) {
      return NextResponse.json({ error: 'Failed to connect to game database' }, { status: 500 })
    }

    let player: any = null
    let vehicles: any[] = []
    let properties: any[] = []
    let inventory: any[] = []

    if (config.framework === 'QBCORE') {
      // Get player data
      const [playerRows] = await pool.query<any[]>(
        `SELECT * FROM players WHERE citizenid = ?`,
        [id]
      )
      
      if (playerRows.length > 0) {
        const row = playerRows[0]
        const charinfo = typeof row.charinfo === 'string' ? JSON.parse(row.charinfo) : row.charinfo || {}
        const money = typeof row.money === 'string' ? JSON.parse(row.money) : row.money || {}
        const job = typeof row.job === 'string' ? JSON.parse(row.job) : row.job || {}
        const gang = typeof row.gang === 'string' ? JSON.parse(row.gang) : row.gang || {}
        const metadata = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata || {}
        const position = typeof row.position === 'string' ? JSON.parse(row.position) : row.position || {}

        player = {
          id: row.citizenid,
          identifier: row.citizenid,
          license: row.license,
          name: `${charinfo.firstname || ''} ${charinfo.lastname || ''}`.trim() || row.name,
          firstName: charinfo.firstname || '',
          lastName: charinfo.lastname || '',
          dateOfBirth: charinfo.birthdate || '',
          gender: charinfo.gender,
          phone: charinfo.phone,
          nationality: charinfo.nationality || '',
          money,
          job,
          gang,
          metadata,
          position,
          discord: row.discord,
          lastUpdated: row.last_updated,
          framework: 'QBCORE',
        }

        // Get vehicles
        const [vehicleRows] = await pool.query<any[]>(
          `SELECT * FROM player_vehicles WHERE citizenid = ?`,
          [id]
        )
        vehicles = vehicleRows.map((v: any) => ({
          plate: v.plate,
          vehicle: v.vehicle,
          garage: v.garage,
          state: v.state,
          fuel: v.fuel,
          engine: v.engine,
          body: v.body,
          mods: typeof v.mods === 'string' ? JSON.parse(v.mods) : v.mods,
        }))

        // Try to get properties (house system varies)
        try {
          const [propRows] = await pool.query<any[]>(
            `SELECT * FROM player_houses WHERE citizenid = ?`,
            [id]
          )
          properties = propRows.map((p: any) => ({
            name: p.house,
            label: p.house,
            keyholders: p.keyholders,
          }))
        } catch {
          // Properties table may not exist
        }

        // Try to get inventory
        try {
          const [invRows] = await pool.query<any[]>(
            `SELECT * FROM inventories WHERE identifier = ?`,
            [`player:${id}`]
          )
          if (invRows.length > 0) {
            const invData = typeof invRows[0].items === 'string' 
              ? JSON.parse(invRows[0].items) 
              : invRows[0].items
            inventory = Object.values(invData || {})
          }
        } catch {
          // Inventory table may not exist or have different structure
        }
      }
    } else {
      // ESX
      const [playerRows] = await pool.query<any[]>(
        `SELECT * FROM users WHERE identifier = ?`,
        [id]
      )
      
      if (playerRows.length > 0) {
        const row = playerRows[0]
        const accounts = typeof row.accounts === 'string' ? JSON.parse(row.accounts) : row.accounts || {}
        const position = typeof row.position === 'string' ? JSON.parse(row.position) : row.position || {}
        const loadout = typeof row.loadout === 'string' ? JSON.parse(row.loadout) : row.loadout || []

        player = {
          id: row.identifier,
          identifier: row.identifier,
          license: row.identifier,
          name: `${row.firstname || ''} ${row.lastname || ''}`.trim() || 'Unknown',
          firstName: row.firstname || '',
          lastName: row.lastname || '',
          dateOfBirth: row.dateofbirth || '',
          gender: row.sex === 'm' ? 0 : row.sex === 'f' ? 1 : null,
          phone: row.phone_number,
          money: {
            cash: accounts.money || accounts.cash || 0,
            bank: accounts.bank || 0,
            black: accounts.black_money || 0,
          },
          job: {
            name: row.job || 'unemployed',
            label: row.job || 'Arbeitslos',
            grade: row.job_grade || 0,
          },
          position,
          loadout,
          discord: row.discord,
          lastUpdated: null,
          framework: 'ESX',
        }

        // Get vehicles
        const [vehicleRows] = await pool.query<any[]>(
          `SELECT * FROM owned_vehicles WHERE owner = ?`,
          [id]
        )
        vehicles = vehicleRows.map((v: any) => ({
          plate: v.plate,
          vehicle: typeof v.vehicle === 'string' ? JSON.parse(v.vehicle) : v.vehicle,
          stored: v.stored === 1,
          garage: v.garage,
          type: v.type,
        }))

        // Try to get properties
        try {
          const [propRows] = await pool.query<any[]>(
            `SELECT * FROM owned_properties WHERE owner = ?`,
            [id]
          )
          properties = propRows.map((p: any) => ({
            name: p.name,
            label: p.label,
          }))
        } catch {
          // Properties table may not exist
        }
      }
    }

    if (!player) {
      return NextResponse.json({ error: 'Player not found' }, { status: 404 })
    }

    // Get admin notes from UCP database (optional - table may not exist)
    let notes: any[] = []
    try {
      notes = await prisma.playerNote.findMany({
        where: { playerId: id },
        orderBy: { createdAt: 'desc' },
        include: {
          author: {
            select: { username: true }
          }
        }
      })
    } catch {
      // Table doesn't exist yet - that's fine, just return empty notes
      console.log('[API] player_notes table not available yet')
    }

    return NextResponse.json({
      player,
      vehicles,
      properties,
      inventory,
      notes,
    })
  } catch (error) {
    console.error('[API] Failed to fetch player details:', error)
    return NextResponse.json(
      { error: 'Failed to fetch player details' },
      { status: 500 }
    )
  }
}
