import { NextResponse } from 'next/server'
import { getCurrentUser } from '@/lib/auth'
import { getGameDbPool, getGameDbConfig } from '@/lib/game-db'
import { prisma } from '@/lib/db'
import type { RowDataPacket } from 'mysql2'

export const dynamic = 'force-dynamic'

export async function GET() {
  const debug: Record<string, unknown> = {}
  
  try {
    // Step 1: Get current user
    const user = await getCurrentUser()
    debug.step1_user = user ? {
      id: user.id,
      name: user.name,
      discordId: user.discordId,
      role: user.role,
    } : null
    
    if (!user) {
      return NextResponse.json({ error: 'Not logged in', debug })
    }
    
    // Step 2: Check game database config
    const config = await getGameDbConfig()
    debug.step2_gameDbConfig = config ? {
      host: config.host,
      database: config.database,
      framework: config.framework,
      hasPassword: !!config.password,
    } : null
    
    if (!config) {
      return NextResponse.json({ error: 'No game database configured', debug })
    }
    
    // Step 3: Check database connection
    const pool = await getGameDbPool()
    debug.step3_poolAvailable = !!pool
    
    if (!pool) {
      return NextResponse.json({ error: 'Could not connect to game database', debug })
    }
    
    // Step 4: Check if players/users table exists and has discord column
    try {
      const tableName = config.framework === 'QBCORE' ? 'players' : 'users'
      const [columns] = await pool.query<RowDataPacket[]>(
        `SHOW COLUMNS FROM ${tableName} LIKE 'discord'`
      )
      debug.step4_discordColumnExists = columns.length > 0
      
      // Get column info
      const [allColumns] = await pool.query<RowDataPacket[]>(
        `SHOW COLUMNS FROM ${tableName}`
      )
      debug.step4_tableColumns = allColumns.map((c: RowDataPacket) => c.Field)
    } catch (e) {
      debug.step4_error = String(e)
    }
    
    // Step 5: Try to find characters with user's Discord ID
    const discordId = user.discordId
    debug.step5_searchingForDiscordId = discordId
    
    if (discordId) {
      try {
        const tableName = config.framework === 'QBCORE' ? 'players' : 'users'
        
        // Direct query
        const [rows] = await pool.query<RowDataPacket[]>(
          `SELECT * FROM ${tableName} WHERE discord = ?`,
          [discordId]
        )
        debug.step5_directQueryResults = rows.length
        debug.step5_firstRow = rows[0] ? {
          id: rows[0].id,
          citizenid: rows[0].citizenid,
          name: rows[0].name,
          discord: rows[0].discord,
        } : null
        
        // Also check what discord values exist in DB
        const [discordValues] = await pool.query<RowDataPacket[]>(
          `SELECT discord, citizenid, name FROM ${tableName} WHERE discord IS NOT NULL LIMIT 10`
        )
        debug.step5_existingDiscordValues = discordValues.map((r: RowDataPacket) => ({
          discord: r.discord,
          citizenid: r.citizenid,
          name: r.name,
        }))
      } catch (e) {
        debug.step5_error = String(e)
      }
    }
    
    // Step 6: Check UCP database for player mapping
    try {
      const mappings = await prisma.playerMapping.findMany({
        where: { discordId: discordId || '' },
        take: 5,
      })
      debug.step6_ucpMappings = mappings
    } catch (e) {
      debug.step6_error = String(e)
    }
    
    return NextResponse.json({ 
      success: true, 
      debug,
      message: 'Check the debug object for detailed information'
    })
    
  } catch (error) {
    return NextResponse.json({ 
      error: String(error), 
      debug 
    }, { status: 500 })
  }
}
