const express = require('express');
const IdleSystem = require('../systems/IdleSystem');

const router = express.Router();

// Initialize idle system
const idleSystem = new IdleSystem();

// Calculate offline progress
router.post('/progress/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const progress = idleSystem.calculateOfflineProgress(userId);
    
    res.json({
      success: true,
      progress: {
        offlineTime: progress.offlineTime,
        offlineSeconds: progress.offlineSeconds,
        rewards: progress.rewards,
        productionRates: progress.productionRates
      }
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Apply idle rewards to player data
router.post('/rewards/apply/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { playerData } = req.body;
    
    if (!playerData) {
      return res.status(400).json({ 
        success: false, 
        error: 'Player data required' 
      });
    }
    
    const progress = idleSystem.applyIdleRewards(userId, playerData);
    
    res.json({
      success: true,
      progress,
      updatedPlayerData: playerData
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Get production rates
router.get('/production/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const productionRates = idleSystem.getProductionRates(userId);
    
    res.json({
      success: true,
      productionRates
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Update production rates
router.post('/production/update/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { rates } = req.body;
    
    if (!rates) {
      return res.status(400).json({ 
        success: false, 
        error: 'Production rates required' 
      });
    }
    
    idleSystem.updateProductionRates(userId, rates);
    const updatedRates = idleSystem.getProductionRates(userId);
    
    res.json({
      success: true,
      productionRates: updatedRates
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Update bonuses
router.post('/bonuses/update/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { bonuses } = req.body;
    
    if (!bonuses) {
      return res.status(400).json({ 
        success: false, 
        error: 'Bonuses required' 
      });
    }
    
    const updatedRates = idleSystem.updateBonuses(userId, bonuses);
    
    res.json({
      success: true,
      productionRates: updatedRates
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Get achievements
router.get('/achievements/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const achievements = idleSystem.getAchievements(userId);
    
    res.json({
      success: true,
      achievements
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Get idle stats
router.get('/stats/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const stats = idleSystem.getIdleStats(userId);
    
    res.json({
      success: true,
      stats
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Calculate income for specific time
router.post('/income/calculate/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { timeInSeconds } = req.body;
    
    if (!timeInSeconds || timeInSeconds <= 0) {
      return res.status(400).json({ 
        success: false, 
        error: 'Valid time in seconds required' 
      });
    }
    
    const income = idleSystem.calculateIncomeForTime(userId, timeInSeconds);
    
    res.json({
      success: true,
      timeInSeconds,
      income
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Get time until milestone
router.get('/milestone/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const targetCredits = parseInt(req.query.target) || 10000;
    const timeUntil = idleSystem.getTimeUntilMilestone(userId, targetCredits);
    
    res.json({
      success: true,
      targetCredits,
      timeUntil
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Update last active time
router.post('/active/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    idleSystem.updateLastActive(userId);
    
    res.json({
      success: true,
      lastActive: new Date().toISOString()
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Get global idle statistics
router.get('/global', async (req, res) => {
  try {
    const globalStats = idleSystem.getGlobalStats();
    
    res.json({
      success: true,
      globalStats
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

// Reset player data (admin only)
router.post('/reset/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    idleSystem.resetPlayerData(userId);
    
    res.json({
      success: true,
      message: 'Player idle data reset successfully'
    });

  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error' 
    });
  }
});

module.exports = router;
