import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { createOrUpdateMapping, type PlayerIdentifiers } from '@/lib/services/identifier-mapping-service'

/**
 * POST /api/fivem/mapping
 * 
 * Called by the FiveM integration script when a player joins the server
 * Creates or updates the identifier mapping for Discord-FiveM linking
 * 
 * Request body:
 * {
 *   apiKey: string (server API key for authentication)
 *   identifiers: {
 *     discord: string (required)
 *     license?: string
 *     steam?: string
 *     fivem?: string
 *     xbl?: string
 *     live?: string
 *     ip?: string
 *   }
 *   gameIdentifier?: string (ESX identifier / QBCore citizenid)
 *   characterId?: string
 * }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { apiKey, identifiers, gameIdentifier, characterId } = body

    // Validate API key
    if (!apiKey) {
      return NextResponse.json(
        { error: 'API key is required' },
        { status: 401 }
      )
    }

    // First try to verify against system UCP API key
    const systemApiKey = await prisma.systemSetting.findUnique({
      where: { key: 'ucpApiKey' },
    })

    let isValidApiKey = false

    if (systemApiKey && systemApiKey.value === apiKey) {
      isValidApiKey = true
    } else {
      // Fallback: check if it's a server-specific API key
      const server = await prisma.server.findUnique({
        where: { apiKey },
      })
      if (server && server.isActive) {
        isValidApiKey = true
      }
    }

    if (!isValidApiKey) {
      console.log('[API FiveM Mapping] Invalid API key attempted:', apiKey?.substring(0, 8) + '...')
      return NextResponse.json(
        { error: 'Invalid API key' },
        { status: 401 }
      )
    }

    // Validate identifiers
    if (!identifiers || !identifiers.discord) {
      return NextResponse.json(
        { error: 'Discord identifier is required' },
        { status: 400 }
      )
    }

    // Create or update the mapping
    const result = await createOrUpdateMapping(
      identifiers as PlayerIdentifiers,
      gameIdentifier,
      characterId
    )

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

    return NextResponse.json({
      success: true,
      created: result.created,
      mapping: {
        discordId: result.mapping?.discordId,
        firstJoinAt: result.mapping?.firstJoinAt,
        lastSeenAt: result.mapping?.lastSeenAt,
      },
    })
  } catch (error) {
    console.error('[API FiveM Mapping] Error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

/**
 * GET /api/fivem/mapping?discord=<discordId>&apiKey=<apiKey>
 * 
 * Check if a Discord ID has a mapping (for FiveM script to check)
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const discordId = searchParams.get('discord')
    const apiKey = searchParams.get('apiKey')

    if (!apiKey) {
      return NextResponse.json(
        { error: 'API key is required' },
        { status: 401 }
      )
    }

    // Validate API key (system key or server key)
    const systemApiKey = await prisma.systemSetting.findUnique({
      where: { key: 'ucpApiKey' },
    })

    let isValidApiKey = false
    if (systemApiKey && systemApiKey.value === apiKey) {
      isValidApiKey = true
    } else {
      const server = await prisma.server.findUnique({
        where: { apiKey },
      })
      if (server && server.isActive) {
        isValidApiKey = true
      }
    }

    if (!isValidApiKey) {
      return NextResponse.json(
        { error: 'Invalid API key' },
        { status: 401 }
      )
    }

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

    const normalizedId = discordId.replace('discord:', '')
    const mapping = await prisma.identifierMapping.findUnique({
      where: { discordId: normalizedId },
    })

    return NextResponse.json({
      exists: !!mapping,
      mapping: mapping ? {
        discordId: mapping.discordId,
        firstJoinAt: mapping.firstJoinAt,
        lastSeenAt: mapping.lastSeenAt,
        gameIdentifier: mapping.gameIdentifier,
      } : null,
    })
  } catch (error) {
    console.error('[API FiveM Mapping GET] Error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
