'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add operation field to permission table
    await queryInterface.addColumn('permission', 'operation', {
      type: Sequelize.STRING(50),
      allowNull: true,
      comment: 'Operation name (e.g., CREATE, EDIT, APPROVE, VIEW, PRINT, EXPORT, CLOSE, REOPEN)',
      after: 'resource'
    });

    // Update existing permissions: convert action to operation
    await queryInterface.sequelize.query(`
      UPDATE permission 
      SET operation = action 
      WHERE operation IS NULL
    `);

    // Make operation NOT NULL after data migration
    await queryInterface.changeColumn('permission', 'operation', {
      type: Sequelize.STRING(50),
      allowNull: false,
      comment: 'Operation name (e.g., CREATE, EDIT, APPROVE, VIEW, PRINT, EXPORT, CLOSE, REOPEN)'
    });

    // Add index on operation
    await queryInterface.addIndex('permission', ['operation'], {
      name: 'idx_permission_operation'
    });

    // Update permission_code to use operation instead of action
    // This will be done in the seeder to regenerate all permission codes
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeIndex('permission', 'idx_permission_operation');
    await queryInterface.removeColumn('permission', 'operation');
  }
};

