const mongoose = require('mongoose');
const logger = require('../utils/logger');
const Player = require('../models/Player');
const Ship = require('../models/Ship');
const Inventory = require('../models/Inventory');
require('dotenv').config();

async function seed() {
  try {
    logger.info('Starting database seeding...');
    
    // Connect to database
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/galaxystrikeonline');
    
    logger.info('Connected to database');
    
    // Clear existing data (optional - remove if you want to preserve data)
    logger.info('Clearing existing data...');
    await Player.deleteMany({});
    await Ship.deleteMany({});
    await Inventory.deleteMany({});
    
    // Create a test user
    const testUser = new Player({
      userId: 'test_user_001',
      username: 'TestPlayer',
      email: 'test@example.com',
      password: '$2a$10$example_hashed_password_here',
      stats: {
        level: 1,
        experience: 0,
        credits: 5000,
        dungeonsCleared: 0,
        playTime: 0,
        lastLogin: new Date()
      },
      attributes: {
        health: 100,
        maxHealth: 100,
        energy: 100,
        maxEnergy: 100,
        attack: 10,
        defense: 5,
        speed: 10,
        criticalChance: 0.05,
        criticalDamage: 1.5
      },
      info: {
        name: 'Commander',
        title: 'Rookie Pilot',
        guild: null,
        rank: 'Cadet'
      },
      settings: {
        autoSave: true,
        notifications: true,
        soundEffects: true,
        music: false,
        discordIntegration: false
      },
      dailyRewards: {
        lastClaim: null,
        consecutiveDays: 0
      }
    });
    
    await testUser.save();
    logger.info('Created test user');
    
    // Create starter ship for test user
    const starterShip = new Ship({
      userId: testUser.userId,
      id: 'starter_cruiser_001',
      name: 'Starter Cruiser',
      class: 'Cruiser',
      level: 1,
      stats: {
        health: 100,
        maxHealth: 100,
        attack: 15,
        defense: 12,
        speed: 10,
        criticalChance: 0.05,
        criticalDamage: 1.5,
        hull: 100
      },
      texture: 'assets/textures/ships/starter_cruiser.png',
      experience: 0,
      requiredExp: 100,
      upgrades: [],
      isEquipped: true,
      isCurrent: true,
      price: 5000,
      rarity: 'common',
      description: 'Reliable starter cruiser for new pilots',
      acquiredAt: new Date(),
      lastUsed: new Date()
    });
    
    await starterShip.save();
    logger.info('Created starter ship');
    
    // Update player with current ship
    testUser.currentShip = starterShip._id;
    await testUser.save();
    
    // Create inventory for test user
    const inventory = new Inventory({
      userId: testUser.userId,
      maxSlots: 50,
      items: [
        {
          id: 'starter_blaster_common',
          name: 'Common Blaster',
          type: 'weapon',
          rarity: 'common',
          quantity: 1,
          stats: {
            attack: 5,
            criticalChance: 0.02,
            damage: 10,
            fireRate: 2,
            range: 5,
            energy: 5
          },
          description: 'A reliable basic blaster for new pilots',
          equipable: true,
          slot: 'weapon',
          isEquipped: false,
          stackable: false,
          acquiredAt: new Date()
        },
        {
          id: 'basic_armor_common',
          name: 'Basic Armor',
          type: 'armor',
          rarity: 'common',
          quantity: 1,
          stats: {
            defense: 3,
            durability: 20,
            weight: 2,
            energyShield: 0
          },
          description: 'Light armor providing basic protection',
          equipable: true,
          slot: 'armor',
          isEquipped: false,
          stackable: false,
          acquiredAt: new Date()
        },
        {
          id: 'health_kit',
          name: 'Health Kit',
          type: 'consumable',
          rarity: 'common',
          quantity: 3,
          stats: {},
          description: 'A medical kit that restores health',
          consumable: true,
          effect: {
            health: 50
          },
          stackable: true,
          acquiredAt: new Date()
        }
      ],
      equippedItems: {
        weapon: null,
        armor: null,
        engine: null,
        shield: null,
        special: null
      }
    });
    
    await inventory.save();
    logger.info('Created inventory with starter items');
    
    logger.info('Database seeding completed successfully');
    
    // Close connection
    await mongoose.connection.close();
    logger.info('Database connection closed');
    
  } catch (error) {
    logger.error('Seeding failed:', error);
    process.exit(1);
  }
}

if (require.main === module) {
  seed();
}

module.exports = seed;
