const express = require('express');

const router = express.Router();

function callLuaExport(exportName, params, callback) {
  try {
    let exportFunc = null;
    
    if (typeof global !== 'undefined' && global.exports && global.exports['rovebots-icmanager']) {
      exportFunc = global.exports['rovebots-icmanager'][exportName];
    } else if (typeof exports !== 'undefined' && exports['rovebots-icmanager']) {
      exportFunc = exports['rovebots-icmanager'][exportName];
    } else if (typeof exports !== 'undefined' && exports[exportName]) {
      exportFunc = exports[exportName];
    } else if (typeof global !== 'undefined' && global.exports && global.exports[exportName]) {
      exportFunc = global.exports[exportName];
    }
    
    if (exportFunc && typeof exportFunc === 'function') {
      exportFunc(params, callback);
    } else {
      callback(new Error(`Lua export function "${exportName}" not found`), null);
    }
  } catch (error) {
    callback(error, null);
  }
}

router.get('/status', (req, res) => {
  res.json({
    status: 'online',
    server: 'ICManager',
    timestamp: new Date().toISOString()
  });
});


router.get('/server/players/db/list', async (req, res) => {
  try {
    const players = await new Promise((resolve, reject) => {
      try {
        let getPlayersFunc = null;
        let foundMethod = null;
        
        if (typeof global !== 'undefined' && global.exports && global.exports['rovebots-icmanager']) {
          getPlayersFunc = global.exports['rovebots-icmanager'].getPlayersFromDB;
          foundMethod = 'global.exports[resourceName]';
        }
        else if (typeof exports !== 'undefined' && exports['rovebots-icmanager']) {
          getPlayersFunc = exports['rovebots-icmanager'].getPlayersFromDB;
          foundMethod = 'exports[resourceName]';
        }
        else if (typeof exports !== 'undefined' && exports.getPlayersFromDB) {
          getPlayersFunc = exports.getPlayersFromDB;
          foundMethod = 'exports.getPlayersFromDB';
        }
        else if (typeof global !== 'undefined' && global.exports && global.exports.getPlayersFromDB) {
          getPlayersFunc = global.exports.getPlayersFromDB;
          foundMethod = 'global.exports.getPlayersFromDB';
        }
        
        if (getPlayersFunc && typeof getPlayersFunc === 'function') {
          console.log(`[API] Found export via ${foundMethod}`);
          getPlayersFunc((error, result) => {
            if (error) {
              console.error('[API] Lua export error:', error);
              reject(new Error(error));
            } else {
              resolve(result);
            }
          });
        } else {
          const exportKeys = typeof exports !== 'undefined' ? Object.keys(exports || {}) : [];
          const globalExportKeys = (typeof global !== 'undefined' && global.exports) ? Object.keys(global.exports || {}) : [];
          console.error('[API] Export function not found.');
          console.error('[API] exports keys:', exportKeys);
          console.error('[API] global.exports keys:', globalExportKeys);
          reject(new Error('Lua export function "getPlayersFromDB" not found. Make sure server_main.lua is loaded and exports the function correctly.'));
        }
      } catch (exportError) {
        console.error('[API] Error calling Lua export:', exportError);
        reject(exportError);
      }
    });

    res.json({
      success: true,
      count: players ? players.length : 0,
      players: players || []
    });
  } catch (error) {
    console.error('[API] Error fetching players from database:', error);
    res.status(500).json({ 
      success: false,
      error: 'Failed to fetch players from database',
      message: error.message 
    });
  }
});

router.post('/server/player/setmoney', async (req, res) => {
  try {
    const { playerId, moneyType, amount } = req.body;
    
    if (!playerId || !moneyType || amount === undefined) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, moneyType (cash/bank), amount'
      });
    }
    
    if (moneyType !== 'cash' && moneyType !== 'bank') {
      return res.status(400).json({
        success: false,
        error: 'moneyType must be either "cash" or "bank"'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('setPlayerMoney', { playerId, moneyType, amount }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error setting player money:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/addmoney', async (req, res) => {
  try {
    const { playerId, moneyType, amount } = req.body;
    
    if (!playerId || !moneyType || amount === undefined) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, moneyType (cash/bank), amount'
      });
    }
    
    if (moneyType !== 'cash' && moneyType !== 'bank') {
      return res.status(400).json({
        success: false,
        error: 'moneyType must be either "cash" or "bank"'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('addPlayerMoney', { playerId, moneyType, amount }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error adding player money:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/removemoney', async (req, res) => {
  try {
    const { playerId, moneyType, amount } = req.body;
    
    if (!playerId || !moneyType || amount === undefined) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, moneyType (cash/bank), amount'
      });
    }
    
    if (moneyType !== 'cash' && moneyType !== 'bank') {
      return res.status(400).json({
        success: false,
        error: 'moneyType must be either "cash" or "bank"'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('removePlayerMoney', { playerId, moneyType, amount }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error removing player money:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/additem', async (req, res) => {
  try {
    const { playerId, item, itemCount = 1 } = req.body;
    
    if (!playerId || !item) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, item'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('addPlayerItem', { playerId, item, itemCount }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error adding player item:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/removeitem', async (req, res) => {
  try {
    const { playerId, item, itemCount = 1 } = req.body;
    
    if (!playerId || !item) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, item'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('removePlayerItem', { playerId, item, itemCount }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error removing player item:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/revive', async (req, res) => {
  try {
    const { playerId } = req.body;
    
    if (!playerId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: playerId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('revivePlayer', { playerId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error reviving player:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/kill', async (req, res) => {
  try {
    const { playerId } = req.body;
    
    if (!playerId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: playerId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('killPlayer', { playerId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error killing player:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/setjob', async (req, res) => {
  try {
    const { playerId, jobName, jobGrade } = req.body;
    
    if (!playerId || !jobName || jobGrade === undefined) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, jobName, jobGrade'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('setPlayerJob', { playerId, jobName, jobGrade }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error setting player job:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/givevehicle', async (req, res) => {
  try {
    const { playerId, carName, plate, fullmod, renk1, renk2, color1, color2 } = req.body;
    
    if (!playerId || !carName) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: playerId, carName'
      });
    }
    
    const finalColor1 = renk1 || color1 || "0 0 0";
    const finalColor2 = renk2 || color2 || "0 0 0";
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('givePlayerVehicle', { 
        playerId, 
        carName, 
        plate, 
        fullmod: fullmod || false,
        renk1: finalColor1,
        renk2: finalColor2
      }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error giving vehicle to player:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/server/player/inventory', async (req, res) => {
  try {
    const { playerId } = req.query;
    
    if (!playerId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: playerId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('getPlayerInventory', { playerId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, inventory: result });
  } catch (error) {
    console.error('[API] Error getting player inventory:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/addwhitelist', async (req, res) => {
  try {
    const { discordId, addedBy } = req.body;
    
    if (!discordId || !addedBy) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: discordId, addedBy'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('addToWhitelist', { discordId, addedBy }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error adding to whitelist:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/removewhitelist', async (req, res) => {
  try {
    const { discordId, removedBy } = req.body;
    
    if (!discordId || !removedBy) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: discordId, removedBy'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('removeFromWhitelist', { discordId, removedBy }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error removing from whitelist:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/server/player/whitelistinfo', async (req, res) => {
  try {
    const { discordId } = req.query;
    
    if (!discordId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: discordId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('getWhitelistInfo', { discordId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, whitelistInfo: result });
  } catch (error) {
    console.error('[API] Error getting whitelist info:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/ban', async (req, res) => {
  try {
    const { discordId, banReason, banDuration, bannedBy } = req.body;
    
    if (!discordId || !banReason || !banDuration || !bannedBy) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: discordId, banReason, banDuration, bannedBy'
      });
    }
    
    const validDurations = ['1 Day', '3 Day', '7 Day', '1 Month', 'Permanent'];
    if (!validDurations.includes(banDuration)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid banDuration. Must be one of: 1 Day, 3 Day, 7 Day, 1 Month, Permanent'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('banPlayer', { discordId, banReason, banDuration, bannedBy }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error banning player:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.post('/server/player/unban', async (req, res) => {
  try {
    const { discordId, unbanReason, unbannedBy } = req.body;
    
    if (!discordId || !unbanReason || !unbannedBy) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameters: discordId, unbanReason, unbannedBy'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('unbanPlayer', { discordId, unbanReason, unbannedBy }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, result });
  } catch (error) {
    console.error('[API] Error unbanning player:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/server/player/baninfo', async (req, res) => {
  try {
    const { discordId } = req.query;
    
    if (!discordId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: discordId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('getBanInfo', { discordId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, banInfo: result });
  } catch (error) {
    console.error('[API] Error getting ban info:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/server/player/info', async (req, res) => {
  try {
    const { playerId } = req.query;
    
    if (!playerId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: playerId'
      });
    }
    
    const result = await new Promise((resolve, reject) => {
      callLuaExport('getPlayerInfo', { playerId }, (error, result) => {
        if (error) reject(new Error(error));
        else resolve(result);
      });
    });
    
    res.json({ success: true, playerInfo: result });
  } catch (error) {
    console.error('[API] Error getting player info:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

module.exports = { apiRoutes: router };

