const fs = require('fs');
const path = require('path');
const { sequelize, User, GymClass } = require('./models');
const dotenv = require('dotenv');
const bcrypt = require('bcryptjs');

// Load env vars
dotenv.config();

// Copy image files from Java project to uploads folder
const copyImages = async () => {
  const sourceDir = path.join(__dirname, '..', 'gym-backend', 'uploads');
  const destDir = path.join(__dirname, 'uploads');
  
  // Create uploads directory if it doesn't exist
  if (!fs.existsSync(destDir)) {
    fs.mkdirSync(destDir, { recursive: true });
  }
  
  // Check if source directory exists
  if (fs.existsSync(sourceDir)) {
    // Get all image files from source directory
    const imageFiles = fs.readdirSync(sourceDir).filter(file => 
      file.endsWith('.png') || file.endsWith('.jpg') || file.endsWith('.jpeg') || file.endsWith('.gif')
    );
    
    // Copy each file to destination
    imageFiles.forEach(file => {
      fs.copyFileSync(path.join(sourceDir, file), path.join(destDir, file));
      console.log(`Copied ${file} to uploads folder`);
    });
  } else {
    console.log('Source directory not found, skipping image copy');
  }
};

// Create default images if they don't exist
const createDefaultImages = async () => {
  const defaultImages = {
    'default-avatar.jpg': 'Default user avatar image',
    'default-class.jpg': 'Default class image',
    'yoga.png': 'Yoga class image',
    'spinning.png': 'Spinning class image',
    'pilates.png': 'Pilates class image',
    'zumba.png': 'Zumba class image',
    'crossfit.png': 'CrossFit class image'
  };
  
  const uploadsDir = path.join(__dirname, 'uploads');
  
  // Create uploads directory if it doesn't exist
  if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
  }
  
  // Create each default image if it doesn't exist
  Object.entries(defaultImages).forEach(([filename, content]) => {
    const filePath = path.join(uploadsDir, filename);
    if (!fs.existsSync(filePath)) {
      fs.writeFileSync(filePath, content);
      console.log(`Created placeholder for ${filename}`);
    }
  });
};

// Import data into DB
const importData = async () => {
  try {
    // Sync database models without force
    await sequelize.sync();
    console.log('Database connected');
    
    // Copy image files from Java project and create defaults
    await copyImages();
    await createDefaultImages();
    
    // Check if demo user already exists
    const existingUser = await User.findOne({ where: { email: 'usuario@ejemplo.com' } });
    
    // Create demo user only if it doesn't exist
    let demoUser;
    if (!existingUser) {
      // Hash password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash('password123', salt);
      
      demoUser = await User.create({
        name: 'Usuario Demo',
        email: 'usuario@ejemplo.com',
        password: hashedPassword,
        profilePicUrl: '/uploads/default-avatar.jpg',
        notificationsEnabled: true
      });
      
      console.log('Demo user created with ID:', demoUser.id);
    } else {
      console.log('Demo user already exists, skipping creation');
      demoUser = existingUser;
    }
    
    // Create demo classes only if they don't exist
    const existingClasses = await GymClass.count();
    
    if (existingClasses === 0) {
      const currentDate = new Date();
      
      const classes = [
        {
          name: 'Yoga',
          description: 'Clase de yoga para todos los niveles',
          instructor: 'María López',
          startTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000),
          endTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 9 * 60 * 60 * 1000),
          maxCapacity: 15,
          currentBookings: 8,
          category: 'Mente y Cuerpo',
          imageUrl: '/uploads/yoga.png'
        },
        {
          name: 'Spinning',
          description: 'Clase de alta intensidad de ciclismo estático',
          instructor: 'Juan Pérez',
          startTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 10 * 60 * 60 * 1000),
          endTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 11 * 60 * 60 * 1000),
          maxCapacity: 20,
          currentBookings: 15,
          category: 'Cardiovascular',
          imageUrl: '/uploads/spinning.png'
        },
        {
          name: 'Pilates',
          description: 'Fortalecimiento de core y flexibilidad',
          instructor: 'Ana García',
          startTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 16 * 60 * 60 * 1000),
          endTime: new Date(currentDate.getTime() + 24 * 60 * 60 * 1000 + 17 * 60 * 60 * 1000),
          maxCapacity: 12,
          currentBookings: 5,
          category: 'Mente y Cuerpo',
          imageUrl: '/uploads/pilates.png'
        },
        {
          name: 'Zumba',
          description: 'Baile y ejercicio cardiovascular',
          instructor: 'Carlos Martínez',
          startTime: new Date(currentDate.getTime() + 48 * 60 * 60 * 1000 + 18 * 60 * 60 * 1000),
          endTime: new Date(currentDate.getTime() + 48 * 60 * 60 * 1000 + 19 * 60 * 60 * 1000),
          maxCapacity: 25,
          currentBookings: 18,
          category: 'Baile',
          imageUrl: '/uploads/zumba.png'
        },
        {
          name: 'CrossFit',
          description: 'Entrenamiento funcional de alta intensidad',
          instructor: 'Roberto Sánchez',
          startTime: new Date(currentDate.getTime() + 48 * 60 * 60 * 1000 + 9 * 60 * 60 * 1000),
          endTime: new Date(currentDate.getTime() + 48 * 60 * 60 * 1000 + 10 * 60 * 60 * 1000),
          maxCapacity: 15,
          currentBookings: 12,
          category: 'Fuerza',
          imageUrl: '/uploads/crossfit.png'
        }
      ];
      
      await GymClass.bulkCreate(classes);
      console.log(`${classes.length} gym classes created`);
    } else {
      console.log(`Classes already exist, skipping class creation`);
    }
    
    console.log('Data import process completed successfully!');
    process.exit();
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
};



    importData();
