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

interface LogEntry {
  id: string
  type: string
  timestamp: Date | string
  details: Record<string, any>
  source?: string
}

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 { searchParams } = new URL(request.url)
    const logType = searchParams.get('type') || 'all'
    const limit = parseInt(searchParams.get('limit') || '50')

    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 })
    }

    const logs: {
      loginLogs: LogEntry[]
      deathLogs: LogEntry[]
      itemTransfers: LogEntry[]
      adminActions: LogEntry[]
    } = {
      loginLogs: [],
      deathLogs: [],
      itemTransfers: [],
      adminActions: [],
    }

    // Admin actions from game server logs
    // Will be populated if admin_logs table exists in game DB

    // Try to get game server logs (depends on what logging system the server uses)
    // Common logging tables: player_logs, logs, ox_inventory_logs, etc.

    // Login Logs
    if (logType === 'all' || logType === 'login') {
      try {
        // Try common login log tables
        const loginTables = ['player_logins', 'login_logs', 'player_logs']
        
        for (const table of loginTables) {
          try {
            const idColumn = config.framework === 'QBCORE' ? 'citizenid' : 'identifier'
            const [rows] = await pool.query<any[]>(
              `SELECT * FROM ${table} WHERE ${idColumn} = ? OR identifier = ? ORDER BY timestamp DESC LIMIT ?`,
              [id, id, limit]
            )
            
            if (rows && rows.length > 0) {
              logs.loginLogs = rows.map((row: any, index: number) => ({
                id: row.id?.toString() || `login-${index}`,
                type: 'login',
                timestamp: row.timestamp || row.created_at || row.date || new Date(),
                details: {
                  action: row.action || (row.type === 'logout' ? 'Logout' : 'Login'),
                  ip: row.ip || row.ip_address,
                  hwid: row.hwid,
                },
                source: 'GameServer'
              }))
              break
            }
          } catch {
            // Table doesn't exist, try next
          }
        }
      } catch {
        // No login logs available
      }
    }

    // Death Logs
    if (logType === 'all' || logType === 'death') {
      try {
        const deathTables = ['player_deaths', 'death_logs', 'deaths']
        
        for (const table of deathTables) {
          try {
            const idColumn = config.framework === 'QBCORE' ? 'citizenid' : 'identifier'
            const [rows] = await pool.query<any[]>(
              `SELECT * FROM ${table} WHERE ${idColumn} = ? OR victim = ? OR killer = ? ORDER BY timestamp DESC LIMIT ?`,
              [id, id, id, limit]
            )
            
            if (rows && rows.length > 0) {
              logs.deathLogs = rows.map((row: any, index: number) => ({
                id: row.id?.toString() || `death-${index}`,
                type: 'death',
                timestamp: row.timestamp || row.created_at || row.date || new Date(),
                details: {
                  killer: row.killer || row.killer_name || 'Unknown',
                  killerWeapon: row.weapon || row.cause || 'Unknown',
                  deathCause: row.cause || row.death_cause || 'Unknown',
                  coords: row.coords || row.position,
                },
                source: 'GameServer'
              }))
              break
            }
          } catch {
            // Table doesn't exist, try next
          }
        }
      } catch {
        // No death logs available
      }
    }

    // Item Transfer Logs
    if (logType === 'all' || logType === 'items') {
      try {
        // Try ox_inventory logs first (most common)
        try {
          const [rows] = await pool.query<any[]>(
            `SELECT * FROM ox_inventory_logs 
             WHERE owner = ? OR toOwner = ? 
             ORDER BY date DESC LIMIT ?`,
            [id, id, limit]
          )
          
          if (rows && rows.length > 0) {
            logs.itemTransfers = rows.map((row: any, index: number) => ({
              id: row.id?.toString() || `item-${index}`,
              type: 'item',
              timestamp: row.date || new Date(),
              details: {
                action: row.action || 'transfer',
                item: row.name || row.item,
                count: row.count || row.amount || 1,
                from: row.owner,
                to: row.toOwner,
                fromSlot: row.fromSlot,
                toSlot: row.toSlot,
              },
              source: 'ox_inventory'
            }))
          }
        } catch {
          // ox_inventory not installed
        }

        // Try qb-inventory logs
        if (logs.itemTransfers.length === 0) {
          try {
            const [rows] = await pool.query<any[]>(
              `SELECT * FROM inventory_logs 
               WHERE sender = ? OR receiver = ? OR citizenid = ?
               ORDER BY timestamp DESC LIMIT ?`,
              [id, id, id, limit]
            )
            
            if (rows && rows.length > 0) {
              logs.itemTransfers = rows.map((row: any, index: number) => ({
                id: row.id?.toString() || `item-${index}`,
                type: 'item',
                timestamp: row.timestamp || row.date || new Date(),
                details: {
                  action: row.action || row.type || 'transfer',
                  item: row.item || row.name,
                  count: row.count || row.amount || 1,
                  from: row.sender || row.from_identifier,
                  to: row.receiver || row.to_identifier,
                },
                source: 'GameServer'
              }))
            }
          } catch {
            // Inventory logs not available
          }
        }
      } catch {
        // No item logs available
      }
    }

    return NextResponse.json({
      logs,
      playerId: id,
      framework: config.framework,
    })
  } catch (error) {
    console.error('[API] Failed to fetch player logs:', error)
    return NextResponse.json(
      { error: 'Failed to fetch player logs' },
      { status: 500 }
    )
  }
}
