/**
 * Migration: Rename Portuguese (pt) fields to Spanish (es)
 * 将葡萄牙语字段重命名为西班牙语字段
 */

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

async function up() {
  const queryInterface = sequelize.getQueryInterface();
  
  console.log('Starting migration: Rename pt fields to es...');
  
  try {
    // 1. Rename category table fields
    console.log('Renaming category.name_pt to name_es...');
    await queryInterface.renameColumn('category', 'name_pt', 'name_es');
    
    // 2. Rename service table fields
    console.log('Renaming service.title_pt to title_es...');
    await queryInterface.renameColumn('service', 'title_pt', 'title_es');
    
    console.log('Renaming service.description_pt to description_es...');
    await queryInterface.renameColumn('service', 'description_pt', 'description_es');
    
    // 3. Rename notification table fields
    console.log('Renaming notification.title_pt to title_es...');
    await queryInterface.renameColumn('notification', 'title_pt', 'title_es');
    
    console.log('Renaming notification.content_pt to content_es...');
    await queryInterface.renameColumn('notification', 'content_pt', 'content_es');
    
    // 4. Rename hot_services table fields
    console.log('Renaming hot_services.name_pt to name_es...');
    await queryInterface.renameColumn('hot_services', 'name_pt', 'name_es');
    
    // 5. Update user language preferences from 'pt' to 'es'
    console.log('Updating user language preferences from pt to es...');
    await sequelize.query("UPDATE `user` SET language = 'es' WHERE language = 'pt'");
    
    console.log('Migration completed successfully!');
  } catch (error) {
    console.error('Migration failed:', error.message);
    throw error;
  }
}

async function down() {
  const queryInterface = sequelize.getQueryInterface();
  
  console.log('Starting rollback: Rename es fields back to pt...');
  
  try {
    // Reverse all the renames
    await queryInterface.renameColumn('category', 'name_es', 'name_pt');
    await queryInterface.renameColumn('service', 'title_es', 'title_pt');
    await queryInterface.renameColumn('service', 'description_es', 'description_pt');
    await queryInterface.renameColumn('notification', 'title_es', 'title_pt');
    await queryInterface.renameColumn('notification', 'content_es', 'content_pt');
    await queryInterface.renameColumn('hot_services', 'name_es', 'name_pt');
    
    // Revert user language preferences
    await sequelize.query("UPDATE `user` SET language = 'pt' WHERE language = 'es'");
    
    console.log('Rollback completed successfully!');
  } catch (error) {
    console.error('Rollback failed:', error.message);
    throw error;
  }
}

module.exports = { up, down };
