const fs = require('fs');
const path = require('path');

/**
 * Tạo migration file mới với format giống Laravel
 * Format: YYYY_MM_DD_HHMMSS_migration_name.js
 */
function makeMigration(migrationName) {
  if (!migrationName) {
    console.error('Error: Migration name is required');
    console.log('\nUsage: node scripts/make-migration.js <migration-name>');
    console.log('Example: node scripts/make-migration.js create_users_table');
    process.exit(1);
  }

  // Tạo timestamp theo format Laravel: YYYY_MM_DD_HHMMSS
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  const timestamp = `${year}_${month}_${day}_${hours}${minutes}${seconds}`;
  const fileName = `${timestamp}_${migrationName}.js`;
  const filePath = path.join(__dirname, fileName);

  // Template migration mẫu
  const template = `require('dotenv').config();
const connectDB = require('../config/database');

/**
 * Migration: ${migrationName}
 * Created: ${now.toLocaleString('vi-VN')}
 */
async function migrate() {
  try {
    // Kết nối database
    await connectDB();
    console.log('Starting migration: ${migrationName}...');
    
    // TODO: Thêm code migration của bạn ở đây
    
    console.log('Migration ${migrationName} completed successfully!');
    
    const mongoose = require('mongoose');
    await mongoose.disconnect();
    process.exit(0);
  } catch (error) {
    console.error('Migration error:', error);
    process.exit(1);
  }
}

// Chạy migration nếu được gọi trực tiếp
if (require.main === module) {
  migrate();
}

module.exports = { migrate };
`;

  // Kiểm tra file đã tồn tại chưa
  if (fs.existsSync(filePath)) {
    console.error(`Error: Migration file already exists: ${fileName}`);
    process.exit(1);
  }

  // Tạo file migration
  try {
    fs.writeFileSync(filePath, template, 'utf8');
    console.log(`Migration created successfully: ${fileName}`);
    console.log(`Path: ${filePath}`);
  } catch (error) {
    console.error('Error creating migration file:', error.message);
    process.exit(1);
  }
}

// Lấy migration name từ command line arguments
const migrationName = process.argv[2];

// Chạy hàm tạo migration
makeMigration(migrationName);

