const logger = require('../utils/logger');

class EconomySystem {
  constructor() {
    this.shopItems = {
      ships: [],
      weapons: [],
      armors: [],
      materials: [],
      consumables: []
    };
    
    this.dailyRewards = {
      baseReward: 100,
      consecutiveBonus: 50,
      maxConsecutiveDays: 30
    };
  }

  async initialize() {
    logger.info('Initializing Economy System...');
    
    // Initialize shop items
    await this.initializeShopItems();
    
    logger.info('Economy System initialized successfully');
  }

  async initializeShopItems() {
    // Ships
    this.shopItems.ships = [
      // Starter Cruiser Variants
      {
        id: 'starter_cruiser_common',
        name: 'Starter Cruiser',
        type: 'ship',
        rarity: 'common',
        price: 5000,
        currency: 'credits',
        description: 'Reliable starter cruiser for new pilots',
        texture: 'assets/textures/ships/starter_cruiser.png',
        stats: { attack: 15, speed: 10, defense: 12, hull: 100 }
      },
      {
        id: 'starter_cruiser_uncommon',
        name: 'Starter Cruiser II',
        type: 'ship',
        rarity: 'uncommon',
        price: 12000,
        currency: 'credits',
        description: 'Upgraded starter cruiser with enhanced systems',
        texture: 'assets/textures/ships/starter_cruiser.png',
        stats: { attack: 18, speed: 12, defense: 15, hull: 120 }
      },
      {
        id: 'starter_cruiser_rare',
        name: 'Starter Cruiser III',
        type: 'ship',
        rarity: 'rare',
        price: 25000,
        currency: 'credits',
        description: 'Elite starter cruiser with advanced weaponry',
        texture: 'assets/textures/ships/starter_cruiser.png',
        stats: { attack: 22, speed: 14, defense: 18, hull: 140 }
      },
      {
        id: 'starter_cruiser_epic',
        name: 'Starter Cruiser IV',
        type: 'ship',
        rarity: 'epic',
        price: 50000,
        currency: 'credits',
        description: 'Master starter cruiser with elite modifications',
        texture: 'assets/textures/ships/starter_cruiser.png',
        stats: { attack: 28, speed: 16, defense: 22, hull: 160 }
      },
      {
        id: 'starter_cruiser_legendary',
        name: 'Starter Cruiser V',
        type: 'ship',
        rarity: 'legendary',
        price: 100000,
        currency: 'credits',
        description: 'Legendary starter cruiser with unparalleled performance',
        texture: 'assets/textures/ships/starter_cruiser.png',
        stats: { attack: 35, speed: 18, defense: 28, hull: 180 }
      }
    ];

    // Weapons
    this.shopItems.weapons = [
      // Starter Blaster Variants
      {
        id: 'starter_blaster_common',
        name: 'Common Blaster',
        type: 'weapon',
        rarity: 'common',
        price: 1000,
        currency: 'credits',
        description: 'Basic blaster for new pilots',
        texture: 'assets/textures/weapons/starter_blaster.png',
        stats: { damage: 10, fireRate: 2, range: 5, energy: 5 }
      },
      {
        id: 'starter_blaster_uncommon',
        name: 'Starter Blaster II',
        type: 'weapon',
        rarity: 'uncommon',
        price: 2500,
        currency: 'credits',
        description: 'Improved blaster with better damage output',
        texture: 'assets/textures/weapons/starter_blaster.png',
        stats: { damage: 12, fireRate: 2.2, range: 5.5, energy: 6 }
      },
      {
        id: 'starter_blaster_rare',
        name: 'Starter Blaster III',
        type: 'weapon',
        rarity: 'rare',
        price: 5000,
        currency: 'credits',
        description: 'Advanced blaster with enhanced capabilities',
        texture: 'assets/textures/weapons/starter_blaster.png',
        stats: { damage: 15, fireRate: 2.5, range: 6, energy: 7 }
      },
      {
        id: 'starter_blaster_epic',
        name: 'Starter Blaster IV',
        type: 'weapon',
        rarity: 'epic',
        price: 10000,
        currency: 'credits',
        description: 'Elite blaster with superior performance',
        texture: 'assets/textures/weapons/starter_blaster.png',
        stats: { damage: 18, fireRate: 3, range: 6.5, energy: 8 }
      },
      {
        id: 'starter_blaster_legendary',
        name: 'Starter Blaster V',
        type: 'weapon',
        rarity: 'legendary',
        price: 20000,
        currency: 'credits',
        description: 'Legendary starter blaster with ultimate power',
        texture: 'assets/textures/weapons/starter_blaster.png',
        stats: { damage: 22, fireRate: 4, range: 7, energy: 10 }
      }
    ];

    // Armors
    this.shopItems.armors = [
      // Basic Armor Variants
      {
        id: 'basic_armor_common',
        name: 'Basic Armor',
        type: 'armor',
        rarity: 'common',
        price: 1500,
        currency: 'credits',
        description: 'Light protection for beginners',
        texture: 'assets/textures/armors/basic_armor.png',
        stats: { defense: 5, durability: 20, weight: 2, energyShield: 0 }
      },
      {
        id: 'basic_armor_uncommon',
        name: 'Basic Armor II',
        type: 'armor',
        rarity: 'uncommon',
        price: 4000,
        currency: 'credits',
        description: 'Improved basic armor with better durability',
        texture: 'assets/textures/armors/basic_armor.png',
        stats: { defense: 7, durability: 25, weight: 2.2, energyShield: 2 }
      },
      {
        id: 'basic_armor_rare',
        name: 'Basic Armor III',
        type: 'armor',
        rarity: 'rare',
        price: 8000,
        currency: 'credits',
        description: 'Enhanced armor with energy shielding',
        texture: 'assets/textures/armors/basic_armor.png',
        stats: { defense: 10, durability: 30, weight: 2.5, energyShield: 5 }
      },
      {
        id: 'basic_armor_epic',
        name: 'Basic Armor IV',
        type: 'armor',
        rarity: 'epic',
        price: 15000,
        currency: 'credits',
        description: 'Elite armor with advanced protection systems',
        texture: 'assets/textures/armors/basic_armor.png',
        stats: { defense: 15, durability: 35, weight: 3, energyShield: 10 }
      },
      {
        id: 'basic_armor_legendary',
        name: 'Basic Armor V',
        type: 'armor',
        rarity: 'legendary',
        price: 30000,
        currency: 'credits',
        description: 'Legendary armor with ultimate protection',
        texture: 'assets/textures/armors/basic_armor.png',
        stats: { defense: 20, durability: 40, weight: 3.5, energyShield: 15 }
      }
    ];

    // Materials
    this.shopItems.materials = [
      {
        id: 'iron_ore',
        name: 'Iron Ore',
        type: 'material',
        rarity: 'common',
        price: 50,
        currency: 'credits',
        description: 'Raw iron ore used for crafting basic weapons and armor',
        stackable: true
      },
      {
        id: 'copper_wire',
        name: 'Copper Wire',
        type: 'material',
        rarity: 'common',
        price: 75,
        currency: 'credits',
        description: 'Copper wiring used in electronic components',
        stackable: true
      },
      {
        id: 'energy_crystal',
        name: 'Energy Crystal',
        type: 'material',
        rarity: 'uncommon',
        price: 200,
        currency: 'credits',
        description: 'Crystallized energy used for powered equipment',
        stackable: true
      },
      {
        id: 'rare_metal',
        name: 'Rare Metal',
        type: 'material',
        rarity: 'rare',
        price: 500,
        currency: 'credits',
        description: 'Rare metallic alloy used for high-end crafting',
        stackable: true
      },
      {
        id: 'advanced_components',
        name: 'Advanced Components',
        type: 'material',
        rarity: 'rare',
        price: 1000,
        currency: 'credits',
        description: 'Sophisticated electronic components for advanced ship systems',
        stackable: true
      }
    ];

    // Consumables
    this.shopItems.consumables = [
      {
        id: 'health_kit',
        name: 'Health Kit',
        type: 'consumable',
        rarity: 'common',
        price: 100,
        currency: 'credits',
        description: 'A medical kit that restores health',
        consumable: true,
        effect: { health: 50 }
      },
      {
        id: 'energy_pack',
        name: 'Energy Pack',
        type: 'consumable',
        rarity: 'common',
        price: 150,
        currency: 'credits',
        description: 'A pack that restores energy',
        consumable: true,
        effect: { energy: 25 }
      },
      {
        id: 'repair_kit',
        name: 'Repair Kit',
        type: 'consumable',
        rarity: 'uncommon',
        price: 300,
        currency: 'credits',
        description: 'A kit that repairs ship damage',
        consumable: true,
        effect: { health: 100 }
      }
    ];

    logger.info(`Shop initialized with ${this.getTotalShopItems()} items`);
  }

  getTotalShopItems() {
    return Object.values(this.shopItems).reduce((total, category) => total + category.length, 0);
  }

  getShopItems(category = null) {
    if (category && this.shopItems[category]) {
      return this.shopItems[category];
    }
    return this.shopItems;
  }

  getItem(itemId) {
    for (const category of Object.values(this.shopItems)) {
      const item = category.find(item => item.id === itemId);
      if (item) return item;
    }
    return null;
  }

  purchaseItem(userId, itemId, quantity = 1) {
    const item = this.getItem(itemId);
    if (!item) {
      throw new Error('Item not found in shop');
    }

    const totalCost = item.price * quantity;
    
    return {
      item,
      quantity,
      totalCost,
      currency: item.currency
    };
  }

  calculateDailyReward(consecutiveDays) {
    const bonusMultiplier = Math.min(consecutiveDays - 1, this.dailyRewards.maxConsecutiveDays - 1);
    const bonusAmount = bonusMultiplier * this.dailyRewards.consecutiveBonus;
    const totalReward = this.dailyRewards.baseReward + bonusAmount;
    
    return {
      baseReward: this.dailyRewards.baseReward,
      consecutiveBonus: bonusAmount,
      totalReward,
      consecutiveDays
    };
  }

  getRandomShopItems(category, count = 6) {
    const items = this.shopItems[category] || [];
    const shuffled = [...items].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, Math.min(count, items.length));
  }

  refreshShopInventory() {
    logger.info('Refreshing shop inventory...');
    // This would typically involve database operations
    // For now, we'll just log the refresh
    return true;
  }

  getShopStats() {
    const stats = {
      totalItems: this.getTotalShopItems(),
      itemsByCategory: {},
      averagePriceByCategory: {}
    };

    for (const [category, items] of Object.entries(this.shopItems)) {
      stats.itemsByCategory[category] = items.length;
      
      if (items.length > 0) {
        const totalPrice = items.reduce((sum, item) => sum + item.price, 0);
        stats.averagePriceByCategory[category] = Math.round(totalPrice / items.length);
      }
    }

    return stats;
  }
}

module.exports = EconomySystem;
