import { NextRequest, NextResponse } from 'next/server'
import { getCurrentUser } from '@/lib/auth'
import { prisma } from '@/lib/db'

export const dynamic = 'force-dynamic'

// Generate config.lua content
function generateConfigLua(settings: {
  ucpUrl: string
  apiKey: string
  framework: string
  debug: boolean
}): string {
  return `--[[
    SKG UCP - FiveM Integration Configuration
    
    Generated automatically from UCP Settings
    Do not edit manually - use the UCP Settings panel instead
]]

Config = {}

-- UCP API URL (your UCP web panel URL)
Config.UcpUrl = "${settings.ucpUrl}"

-- UCP API Key (automatically generated)
Config.ApiKey = "${settings.apiKey}"

-- Framework detection
-- Options: "auto", "esx", "qbcore"
Config.Framework = "${settings.framework}"

-- Enable debug messages in server console
Config.Debug = ${settings.debug}

-- Sync interval in minutes
Config.SyncInterval = 5

-- Discord requirement
Config.RequireDiscord = false
Config.NoDiscordMessage = "Du musst Discord mit deinem FiveM Account verknuepfen."
`
}

// Generate fxmanifest.lua
function generateFxmanifest(): string {
  return `fx_version 'cerulean'
game 'gta5'

name 'skg-ucp'
description 'SKG UCP - FiveM Integration'
author 'SKG Development'
version '2.1.0'

shared_script 'config.lua'

client_scripts {
    'client/mugshot.lua',
}

server_scripts {
    '@oxmysql/lib/MySQL.lua',
    'server/main.lua',
}

dependencies {
    '/server:5181',
}
`
}

// Generate server/main.lua
function generateServerMain(): string {
  return `-- SKG UCP - FiveM Server Integration
-- Generated from UCP

local UcpConfig = {
    UCP_URL = Config.UcpUrl or "http://localhost:3000",
    API_KEY = Config.ApiKey or "",
    Framework = nil,
    Ready = false,
    DEBUG = Config.Debug or false,
}

local function DebugLog(...)
    if UcpConfig.DEBUG then print("[SKG-UCP]", ...) end
end

local function HasMySQL()
    return MySQL ~= nil and MySQL.query ~= nil
end

local function DetectFramework()
    if Config.Framework and Config.Framework ~= "auto" then
        UcpConfig.Framework = Config.Framework == "qbcore" and "qbcore" or "esx"
        return
    end
    if GetResourceState('qb-core') == 'started' then
        UcpConfig.Framework = "qbcore"
    elseif GetResourceState('es_extended') == 'started' then
        UcpConfig.Framework = "esx"
    end
end

local function GetPlayerIdentifiers(source)
    local identifiers = { discord = nil, license = nil }
    for i = 0, GetNumPlayerIdentifiers(source) - 1 do
        local id = GetPlayerIdentifier(source, i)
        if id then
            if string.find(id, "discord:") then
                identifiers.discord = string.gsub(id, "discord:", "")
            elseif string.find(id, "license:") then
                identifiers.license = id
            end
        end
    end
    return identifiers
end

local discordColumnReady = false

local function EnsureDiscordColumnExists()
    if not HasMySQL() then return false end
    local tableName = UcpConfig.Framework == "qbcore" and "players" or "users"
    pcall(function()
        local result = MySQL.query.await(
            "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = 'discord'",
            { tableName }
        )
        if not result or #result == 0 then
            print("[SKG-UCP] Adding discord column to " .. tableName)
            MySQL.query.await("ALTER TABLE " .. tableName .. " ADD COLUMN discord VARCHAR(50) DEFAULT NULL")
        end
        discordColumnReady = true
    end)
    return discordColumnReady
end

local function SaveDiscordToDb(discordId, identifier)
    if not HasMySQL() or not discordId then return end
    if not discordColumnReady then EnsureDiscordColumnExists() end
    pcall(function()
        if UcpConfig.Framework == "qbcore" then
            MySQL.update.await("UPDATE players SET discord = ? WHERE citizenid = ?", { discordId, identifier })
        else
            MySQL.update.await("UPDATE users SET discord = ? WHERE identifier = ?", { discordId, identifier })
        end
    end)
end

local function OnPlayerLoaded(source, playerData)
    local ids = GetPlayerIdentifiers(source)
    if ids.discord then
        local citizenid = playerData and (playerData.citizenid or (playerData.PlayerData and playerData.PlayerData.citizenid))
        if citizenid then
            SaveDiscordToDb(ids.discord, citizenid)
            DebugLog("Saved Discord for:", citizenid)
        end
    end
    TriggerClientEvent('skg-ucp:captureMugshot', source)
end

local function RegisterFrameworkEvents()
    if UcpConfig.Framework == "qbcore" then
        RegisterNetEvent('QBCore:Server:PlayerLoaded', function()
            local src = source
            local QBCore = exports['qb-core']:GetCoreObject()
            local Player = QBCore.Functions.GetPlayer(src)
            if Player then OnPlayerLoaded(src, Player.PlayerData) end
        end)
    else
        RegisterNetEvent('esx:playerLoaded', function(playerId, xPlayer)
            OnPlayerLoaded(playerId, xPlayer)
        end)
    end
end

RegisterNetEvent('skg-ucp:uploadMugshot', function(characterId, imageData)
    if not characterId or not imageData then return end
    PerformHttpRequest(UcpConfig.UCP_URL .. '/api/mugshot/upload', function(code)
        DebugLog("Mugshot upload:", code == 200 and "success" or "failed")
    end, 'POST', json.encode({
        characterId = characterId,
        imageData = imageData,
        apiKey = UcpConfig.API_KEY,
    }), { ['Content-Type'] = 'application/json' })
end)

RegisterCommand("ucp_status", function(source)
    if source ~= 0 then return end
    print("[SKG-UCP] Status: Ready=" .. tostring(UcpConfig.Ready) .. ", Framework=" .. (UcpConfig.Framework or "None"))
end, true)

RegisterCommand("ucp_debug", function(source)
    if source ~= 0 then return end
    UcpConfig.DEBUG = not UcpConfig.DEBUG
    print("[SKG-UCP] Debug:", UcpConfig.DEBUG and "ON" or "OFF")
end, true)

CreateThread(function()
    Wait(2000)
    DetectFramework()
    Wait(1000)
    if HasMySQL() and UcpConfig.Framework then
        EnsureDiscordColumnExists()
    end
    RegisterFrameworkEvents()
    UcpConfig.Ready = true
    print("========================================")
    print("[SKG-UCP] Loaded - Framework: " .. (UcpConfig.Framework or "None"))
    print("[SKG-UCP] UCP URL: " .. UcpConfig.UCP_URL)
    print("========================================")
end)
`
}

// Generate client/mugshot.lua
function generateClientMugshot(): string {
  return `-- SKG UCP - Client Mugshot
local isTaking = false
local taken = false

local function GetCharacterId()
    if GetResourceState('qb-core') == 'started' then
        local QBCore = exports['qb-core']:GetCoreObject()
        local pd = QBCore.Functions.GetPlayerData()
        return pd and pd.citizenid
    elseif GetResourceState('es_extended') == 'started' then
        local ESX = exports['es_extended']:getSharedObject()
        local pd = ESX.GetPlayerData()
        return pd and pd.identifier
    end
    return nil
end

local function CaptureMugshot()
    if isTaking or taken then return end
    local characterId = GetCharacterId()
    if not characterId then
        Wait(2000)
        characterId = GetCharacterId()
        if not characterId then return end
    end
    
    isTaking = true
    local ped = PlayerPedId()
    local coords = GetEntityCoords(ped)
    local heading = GetEntityHeading(ped)
    
    local camCoords = coords + vector3(
        -math.sin(math.rad(heading)) * 0.8,
        math.cos(math.rad(heading)) * 0.8,
        0.6
    )
    
    local cam = CreateCam("DEFAULT_SCRIPTED_CAMERA", true)
    SetCamCoord(cam, camCoords.x, camCoords.y, camCoords.z)
    PointCamAtCoord(cam, coords.x, coords.y, coords.z + 0.6)
    SetCamActive(cam, true)
    RenderScriptCams(true, false, 0, true, true)
    DisplayRadar(false)
    DisplayHud(false)
    
    Wait(500)
    
    if GetResourceState('screenshot-basic') == 'started' then
        exports['screenshot-basic']:requestScreenshotUpload(
            Config.UcpUrl .. '/api/mugshot/upload',
            'file',
            { headers = { ['X-Character-Id'] = characterId, ['X-Api-Key'] = Config.ApiKey } },
            function() taken = true end
        )
    end
    
    Wait(500)
    RenderScriptCams(false, false, 0, true, true)
    DestroyCam(cam, false)
    DisplayRadar(true)
    DisplayHud(true)
    isTaking = false
end

RegisterNetEvent('skg-ucp:captureMugshot', function()
    Wait(3000)
    CaptureMugshot()
end)

RegisterCommand('updatemugshot', function()
    taken = false
    CaptureMugshot()
end, false)
`
}

// Generate README
function generateReadme(ucpUrl: string, framework: string): string {
  return `# SKG UCP - FiveM Integration

## Installation

1. Copy 'skg-ucp' folder to your server's resources directory
2. Add 'ensure skg-ucp' to server.cfg (after oxmysql)
3. Restart server

## Requirements

- oxmysql
- screenshot-basic (optional, for mugshots)

## Configuration

Framework: ${framework}
UCP URL: ${ucpUrl}
Generated: ${new Date().toISOString()}

## Commands

Console:
- ucp_status - Show status
- ucp_debug - Toggle debug

Player:
- /updatemugshot - Update character photo
`
}

export async function GET(request: NextRequest) {
  try {
    const user = await getCurrentUser()
    
    if (!user || user.role !== 'SUPERADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Get framework from query params
    const searchParams = request.nextUrl.searchParams
    const framework = searchParams.get('framework') || 'auto'

    // Get API key
    const apiKey = await prisma.apiKey.findFirst({
      where: { isActive: true },
    })

    // Get system settings
    const systemSettings = await prisma.systemSetting.findMany()
    const settingsMap: Record<string, string> = {}
    systemSettings.forEach(s => {
      settingsMap[s.key] = s.value
    })

    // Use request origin as fallback for UCP URL
    const host = request.headers.get('host') || 'localhost:3000'
    const ucpUrl = settingsMap.serverUrl || settingsMap.ucpUrl || `http://${host}`

    // Return files as JSON - client will create ZIP using JSZip
    const files: Record<string, string> = {
      'skg-ucp/fxmanifest.lua': generateFxmanifest(),
      'skg-ucp/config.lua': generateConfigLua({
        ucpUrl,
        apiKey: apiKey?.key || 'GENERATE_IN_UCP',
        framework,
        debug: false,
      }),
      'skg-ucp/server/main.lua': generateServerMain(),
      'skg-ucp/client/mugshot.lua': generateClientMugshot(),
      'skg-ucp/README.md': generateReadme(ucpUrl, framework),
    }

    return NextResponse.json({ 
      success: true,
      files,
      framework,
      ucpUrl 
    })

  } catch (error) {
    console.error('[FiveM Resource] Error:', error)
    return NextResponse.json({ 
      error: 'Failed to generate resource',
      details: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 })
  }
}
