import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth'
import { 
  getAllMappings, 
  getMappingStats,
  deleteMapping 
} from '@/lib/services/identifier-mapping-service'
import { getPlayerLinkStatus, manuallyLinkPlayer } from '@/lib/services/player-access-service'

/**
 * GET /api/admin/mappings
 * 
 * Get all identifier mappings (admin function)
 * Query params:
 * - limit: number (default 50)
 * - offset: number (default 0)
 * - search: string (optional)
 * - stats: boolean (if true, return only stats)
 */
export async function GET(request: NextRequest) {
  try {
    const user = await requireAdmin()
    
    const { searchParams } = new URL(request.url)
    const limit = parseInt(searchParams.get('limit') || '50')
    const offset = parseInt(searchParams.get('offset') || '0')
    const search = searchParams.get('search') || undefined
    const statsOnly = searchParams.get('stats') === 'true'

    if (statsOnly) {
      const stats = await getMappingStats()
      return NextResponse.json(stats)
    }

    const result = await getAllMappings({ limit, offset, search })
    return NextResponse.json(result)
  } catch (error) {
    if (error instanceof Error && error.message === 'Unauthorized') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    if (error instanceof Error && error.message === 'Forbidden') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }
    console.error('[API Admin Mappings] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

/**
 * POST /api/admin/mappings
 * 
 * Manually link a Discord account to a game identifier
 * Body:
 * - discordId: string
 * - gameIdentifier: string
 */
export async function POST(request: NextRequest) {
  try {
    const user = await requireAdmin()
    
    const body = await request.json()
    const { discordId, gameIdentifier } = body

    if (!discordId || !gameIdentifier) {
      return NextResponse.json(
        { error: 'discordId and gameIdentifier are required' },
        { status: 400 }
      )
    }

    const result = await manuallyLinkPlayer(discordId, gameIdentifier, user.id)

    if (!result.success) {
      return NextResponse.json({ error: result.error }, { status: 500 })
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    if (error instanceof Error && error.message === 'Unauthorized') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    if (error instanceof Error && error.message === 'Forbidden') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }
    console.error('[API Admin Mappings POST] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

/**
 * DELETE /api/admin/mappings
 * 
 * Delete a mapping
 * Query params:
 * - discordId: string
 */
export async function DELETE(request: NextRequest) {
  try {
    const user = await requireAdmin()
    
    const { searchParams } = new URL(request.url)
    const discordId = searchParams.get('discordId')

    if (!discordId) {
      return NextResponse.json(
        { error: 'discordId is required' },
        { status: 400 }
      )
    }

    const success = await deleteMapping(discordId)

    if (!success) {
      return NextResponse.json({ error: 'Failed to delete mapping' }, { status: 500 })
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    if (error instanceof Error && error.message === 'Unauthorized') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    if (error instanceof Error && error.message === 'Forbidden') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }
    console.error('[API Admin Mappings DELETE] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
