'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const table = await queryInterface.describeTable('cost_center');

    if (!table.operation_name_id) {
      await queryInterface.addColumn('cost_center', 'operation_name_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'operation_name',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        after: 'department_id',
      });
    }

    if (!table.cost_per_hour) {
      await queryInterface.addColumn('cost_center', 'cost_per_hour', {
        type: Sequelize.DECIMAL(15, 3),
        allowNull: true,
        defaultValue: 0.000,
        comment: 'Operation cost per hour used in production costing',
        after: 'currency_id',
      });
    }

    if (!table.standard_time) {
      await queryInterface.addColumn('cost_center', 'standard_time', {
        type: Sequelize.DECIMAL(15, 3),
        allowNull: true,
        defaultValue: 0.000,
        comment: 'Standard operation time in hours',
        after: 'cost_per_hour',
      });
    }

    await queryInterface.addIndex('cost_center', ['operation_name_id'], {
      name: 'idx_cost_center_operation_name_id',
    });
  },

  async down(queryInterface) {
    const table = await queryInterface.describeTable('cost_center');

    try {
      await queryInterface.removeIndex('cost_center', 'idx_cost_center_operation_name_id');
    } catch (error) {
      // index may not exist in some environments
    }

    if (table.standard_time) {
      await queryInterface.removeColumn('cost_center', 'standard_time');
    }
    if (table.cost_per_hour) {
      await queryInterface.removeColumn('cost_center', 'cost_per_hour');
    }
    if (table.operation_name_id) {
      await queryInterface.removeColumn('cost_center', 'operation_name_id');
    }
  },
};
