/**
 * Database Initialization Script
 * This script runs all migrations and seeds the database with initial data
 */

const { sequelize } = require('../config/database');
const logger = require('../config/logger');
const path = require('path');
const fs = require('fs');

const initDatabase = async () => {
  try {
    logger.info('Starting database initialization...');

    // Get all migration files
    const migrationsDir = path.join(__dirname, '../migrations');
    const migrationFiles = fs.readdirSync(migrationsDir)
      .filter(file => file.endsWith('.js'))
      .sort();

    // Run migrations
    logger.info(`Found ${migrationFiles.length} migration files`);
    for (const file of migrationFiles) {
      const migration = require(path.join(migrationsDir, file));
      logger.info(`Running migration: ${file}`);
      try {
        await migration.up(sequelize.getQueryInterface(), sequelize.Sequelize);
        logger.info(`✓ Migration completed: ${file}`);
      } catch (error) {
        // Skip if tables already exist
        if (error.message && error.message.includes('already exists')) {
          logger.info(`⊘ Migration skipped (already exists): ${file}`);
        } else if (error.message && error.message.includes('Duplicate')) {
          logger.info(`⊘ Migration skipped (duplicate key): ${file}`);
        } else {
          throw error;
        }
      }
    }

    // Get all seeder files
    const seedersDir = path.join(__dirname, '../seeders');
    if (fs.existsSync(seedersDir)) {
      const seederFiles = fs.readdirSync(seedersDir)
        .filter(file => file.endsWith('.js'))
        .sort();

      logger.info(`Found ${seederFiles.length} seeder files`);
      for (const file of seederFiles) {
        const seeder = require(path.join(seedersDir, file));
        logger.info(`Running seeder: ${file}`);
        await seeder.up(sequelize.getQueryInterface(), sequelize.Sequelize);
        logger.info(`✓ Seeder completed: ${file}`);
      }
    }

    // Create default admin account
    logger.info('Creating default admin account...');
    const Admin = require('../models/Admin');
    const bcrypt = require('bcrypt');
    
    const existingAdmin = await Admin.findOne({ where: { username: 'admin' } });
    if (!existingAdmin) {
      const hashedPassword = await bcrypt.hash('admin123', 10);
      await Admin.create({
        username: 'admin',
        password: hashedPassword,
        email: 'admin@example.com',
        role: 'super_admin',
        status: 'active',
      });
      logger.info('✓ Default admin account created (username: admin, password: admin123)');
    } else {
      logger.info('✓ Admin account already exists');
    }

    logger.info('✓ Database initialization completed successfully!');
    process.exit(0);
  } catch (error) {
    logger.error('Database initialization failed:', error);
    process.exit(1);
  }
};

// Run if this file is executed directly
if (require.main === module) {
  initDatabase();
}

module.exports = initDatabase;
