'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.addColumn('purchase_order', 'is_edited', {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      after: 'posted_by'
    });

    await queryInterface.addColumn('purchase_order', 'previous_status', {
      type: Sequelize.STRING(30),
      allowNull: true,
      after: 'is_edited'
    });

    await queryInterface.addColumn('purchase_order', 'rev_no', {
      type: Sequelize.INTEGER,
      allowNull: false,
      defaultValue: 0,
      after: 'previous_status'
    });

    await queryInterface.createTable('purchase_order_rate_history', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      po_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'purchase_order',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      item_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'purchase_order_item',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      old_rate: {
        type: Sequelize.DECIMAL(18, 2),
        allowNull: false
      },
      new_rate: {
        type: Sequelize.DECIMAL(18, 2),
        allowNull: false
      },
      changed_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      changed_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      revision_number: {
        type: Sequelize.INTEGER,
        allowNull: false
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex('purchase_order_rate_history', ['po_id']);
    await queryInterface.addIndex('purchase_order_rate_history', ['item_id']);
    await queryInterface.addIndex('purchase_order_rate_history', ['changed_by']);
    await queryInterface.addIndex('purchase_order_rate_history', ['changed_at']);
    await queryInterface.addIndex('purchase_order_rate_history', ['revision_number']);
  },

  async down(queryInterface) {
    await queryInterface.dropTable('purchase_order_rate_history');
    await queryInterface.removeColumn('purchase_order', 'rev_no');
    await queryInterface.removeColumn('purchase_order', 'previous_status');
    await queryInterface.removeColumn('purchase_order', 'is_edited');
  }
};
