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

const router = express.Router();

// Initialize ship system
const shipSystem = new ShipSystem();

// Get all ship templates
router.get('/templates', async (req, res) => {
  try {
    const templates = shipSystem.getAllShipTemplates();
    res.json({
      success: true,
      templates
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get ship templates by class
router.get('/templates/class/:shipClass', async (req, res) => {
  try {
    const { shipClass } = req.params;
    const templates = shipSystem.getShipTemplatesByClass(shipClass);
    
    res.json({
      success: true,
      templates
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get ship templates by rarity
router.get('/templates/rarity/:rarity', async (req, res) => {
  try {
    const { rarity } = req.params;
    const templates = shipSystem.getShipTemplatesByRarity(rarity);
    
    res.json({
      success: true,
      templates
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get available ships for player
router.get('/available/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { playerLevel = 1 } = req.query;
    const ships = shipSystem.getAvailableShips(userId, parseInt(playerLevel));
    
    res.json({
      success: true,
      ships
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get player ships
router.get('/player/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const ships = shipSystem.getPlayerShips(userId);
    
    res.json({
      success: true,
      ships: ships.map(ship => ({
        id: ship.id,
        name: ship.name,
        class: ship.class,
        rarity: ship.rarity,
        level: ship.level,
        experience: ship.experience,
        requiredExp: ship.requiredExp,
        stats: ship.stats,
        maxStats: ship.maxStats,
        slots: ship.slots,
        equippedItems: ship.equippedItems,
        texture: ship.texture,
        status: ship.status,
        createdAt: ship.createdAt,
        lastUsed: ship.lastUsed
      }))
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get specific ship
router.get('/player/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const ship = shipSystem.getShip(userId, shipId);
    
    if (!ship) {
      return res.status(404).json({ 
        success: false, 
        error: 'Ship not found' 
      });
    }
    
    res.json({
      success: true,
      ship: {
        id: ship.id,
        name: ship.name,
        class: ship.class,
        rarity: ship.rarity,
        level: ship.level,
        experience: ship.experience,
        requiredExp: ship.requiredExp,
        stats: ship.stats,
        maxStats: ship.maxStats,
        slots: ship.slots,
        equippedItems: ship.equippedItems,
        texture: ship.texture,
        status: ship.status,
        createdAt: ship.createdAt,
        lastUsed: ship.lastUsed
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get current ship
router.get('/current/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const currentShip = shipSystem.getCurrentShip(userId);
    
    if (!currentShip) {
      return res.status(404).json({ 
        success: false, 
        error: 'No current ship found' 
      });
    }
    
    res.json({
      success: true,
      ship: {
        id: currentShip.id,
        name: currentShip.name,
        class: currentShip.class,
        rarity: currentShip.rarity,
        level: currentShip.level,
        experience: currentShip.experience,
        requiredExp: currentShip.requiredExp,
        stats: currentShip.stats,
        maxStats: currentShip.maxStats,
        slots: currentShip.slots,
        equippedItems: currentShip.equippedItems,
        texture: currentShip.texture,
        status: currentShip.status
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Create new ship
router.post('/create/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { templateId, name, level = 1 } = req.body;
    
    if (!templateId) {
      return res.status(400).json({ 
        success: false, 
        error: 'Ship template ID required' 
      });
    }
    
    const ship = shipSystem.createShip(userId, templateId, { name, level });
    const playerShips = shipSystem.getPlayerShips(userId);
    playerShips.push(ship);
    
    res.json({
      success: true,
      ship: {
        id: ship.id,
        name: ship.name,
        class: ship.class,
        rarity: ship.rarity,
        level: ship.level,
        experience: ship.experience,
        requiredExp: ship.requiredExp,
        stats: ship.stats,
        maxStats: ship.maxStats,
        slots: ship.slots,
        equippedItems: ship.equippedItems,
        texture: ship.texture,
        status: ship.status,
        createdAt: ship.createdAt
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Set current ship
router.post('/current/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const ship = shipSystem.setCurrentShip(userId, shipId);
    
    res.json({
      success: true,
      ship: {
        id: ship.id,
        name: ship.name,
        class: ship.class,
        level: ship.level,
        stats: ship.stats,
        status: ship.status,
        lastUsed: ship.lastUsed
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Add experience to ship
router.post('/experience/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const { amount } = req.body;
    
    if (!amount || amount <= 0) {
      return res.status(400).json({ 
        success: false, 
        error: 'Valid experience amount required' 
      });
    }
    
    const result = shipSystem.addExperience(userId, shipId, amount);
    
    res.json({
      success: true,
      result: {
        experienceGained: result.experienceGained,
        levelsGained: result.levelsGained,
        newLevel: result.newLevel,
        newStats: result.newStats
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Upgrade ship
router.post('/upgrade/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const { upgradeType } = req.body;
    
    if (!upgradeType) {
      return res.status(400).json({ 
        success: false, 
        error: 'Upgrade type required' 
      });
    }
    
    const result = shipSystem.upgradeShip(userId, shipId, upgradeType);
    
    res.json({
      success: true,
      result: {
        upgradeType: result.upgradeType,
        newStats: result.newStats
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Equip item to ship
router.post('/equip/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const { slot, itemId } = req.body;
    
    if (!slot || !itemId) {
      return res.status(400).json({ 
        success: false, 
        error: 'Slot and item ID required' 
      });
    }
    
    const result = shipSystem.equipItem(userId, shipId, slot, itemId);
    
    res.json({
      success: true,
      result: {
        slot: result.slot,
        itemId: result.itemId,
        equippedItems: result.equippedItems
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Unequip item from ship
router.post('/unequip/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const { slot } = req.body;
    
    if (!slot) {
      return res.status(400).json({ 
        success: false, 
        error: 'Slot required' 
      });
    }
    
    const result = shipSystem.unequipItem(userId, shipId, slot);
    
    res.json({
      success: true,
      result: {
        slot: result.slot,
        itemId: result.itemId,
        equippedItems: result.equippedItems
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Repair ship
router.post('/repair/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const { amount } = req.body;
    
    const result = shipSystem.repairShip(userId, shipId, amount);
    
    res.json({
      success: true,
      result: {
        health: result.health,
        maxHealth: result.maxHealth,
        repaired: result.repaired
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Delete ship
router.delete('/:userId/:shipId', async (req, res) => {
  try {
    const { userId, shipId } = req.params;
    const deletedShip = shipSystem.deleteShip(userId, shipId);
    
    res.json({
      success: true,
      deletedShip: {
        id: deletedShip.id,
        name: deletedShip.name,
        class: deletedShip.class
      }
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

// Get ship statistics
router.get('/stats/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const stats = shipSystem.getPlayerShipStats(userId);
    
    res.json({
      success: true,
      stats
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

module.exports = router;
