import { NextResponse } from 'next/server'
import { getCurrentUser } from '@/lib/auth'
import { getCharactersByDiscordId, getAllCharacters, getCharactersByLicense } from '@/lib/services/character-service'
import { prisma } from '@/lib/db'

/**
 * GET /api/characters
 * Returns characters for the current user from game database
 * Or all characters for admin with ?all=true
 */
export async function GET(request: Request) {
  try {
    const user = await getCurrentUser()
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { searchParams } = new URL(request.url)
    const all = searchParams.get('all') === 'true'
    const search = searchParams.get('search') || undefined
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const offset = (page - 1) * limit

    // Admin can get all characters
    if (all && (user.role === 'ADMIN' || user.role === 'SUPERADMIN')) {
      const { characters, total } = await getAllCharacters(limit, offset, search)
      return NextResponse.json({
        characters,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      })
    }

    // Get current user's Discord account
    const discordAccount = await prisma.discordAccount.findUnique({
      where: { userId: user.id },
    })

    if (!discordAccount) {
      return NextResponse.json({ 
        characters: [],
        message: 'No Discord account linked',
        hasMapping: false,
      })
    }

    // Check identifier mapping for license
    const mapping = await prisma.identifierMapping.findUnique({
      where: { discordId: discordAccount.discordId },
    })

    let characters = []

    // Try to get characters by license first (more reliable)
    if (mapping?.license) {
      characters = await getCharactersByLicense(mapping.license)
    }
    
    // Fallback to Discord ID search
    if (characters.length === 0) {
      characters = await getCharactersByDiscordId(discordAccount.discordId)
    }

    return NextResponse.json({
      characters,
      mapping: mapping ? {
        license: mapping.license,
        gameIdentifier: mapping.gameIdentifier,
        characterId: mapping.characterId,
        lastSeen: mapping.lastSeenAt,
        firstJoin: mapping.firstJoinAt,
      } : null,
      hasMapping: !!mapping,
      multiCharacter: characters.length > 1,
    })
  } catch (error) {
    console.error('[API] Error fetching characters:', error)
    return NextResponse.json({ 
      error: 'Internal server error',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, { status: 500 })
  }
}
