import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { prisma } from '@/lib/db'
import { getPlayerProfile, syncPlayerToUCP } from '@/lib/services/player-service'

export async function GET() {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Get user's Discord ID
    const user = await prisma.user.findUnique({
      where: { id: session.userId },
      select: { discordId: true, id: true }
    })

    if (!user?.discordId) {
      return NextResponse.json({ error: 'Discord account not linked' }, { status: 400 })
    }

    // Get player profile from game database
    const profile = await getPlayerProfile(user.discordId)

    if (!profile) {
      return NextResponse.json({ 
        error: 'Player not found',
        message: 'No character found linked to your Discord account. Make sure you have joined the server with your Discord linked.'
      }, { status: 404 })
    }

    // Sync to UCP database in background
    syncPlayerToUCP(user.discordId, user.id).catch(console.error)

    return NextResponse.json(profile)
  } catch (error) {
    console.error('[API] Error fetching player profile:', error)
    return NextResponse.json(
      { error: 'Failed to fetch player profile' },
      { status: 500 }
    )
  }
}

export async function POST() {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Get user's Discord ID
    const user = await prisma.user.findUnique({
      where: { id: session.userId },
      select: { discordId: true, id: true }
    })

    if (!user?.discordId) {
      return NextResponse.json({ error: 'Discord account not linked' }, { status: 400 })
    }

    // Force sync player data
    const success = await syncPlayerToUCP(user.discordId, user.id)

    if (!success) {
      return NextResponse.json({ 
        error: 'Sync failed',
        message: 'Could not sync player data. Make sure your Discord is linked in-game.'
      }, { status: 400 })
    }

    return NextResponse.json({ success: true, message: 'Player data synced successfully' })
  } catch (error) {
    console.error('[API] Error syncing player:', error)
    return NextResponse.json(
      { error: 'Failed to sync player data' },
      { status: 500 }
    )
  }
}
