'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('uom_conversion', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      from_uom_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'uom',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      to_uom_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'uom',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      conversion_factor: {
        type: Sequelize.DECIMAL(15, 6),
        allowNull: false,
        defaultValue: 1.000000,
        comment: 'Conversion factor: to_uom = from_uom * conversion_factor'
      },
      material_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        comment: 'NULL for generic conversion, specific material ID for material-specific conversion'
      },
      status: {
        type: Sequelize.ENUM('ACTIVE', 'INACTIVE'),
        allowNull: false,
        defaultValue: 'ACTIVE'
      },
      effective_from: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      effective_to: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      created_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      updated_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      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('uom_conversion', ['from_uom_id', 'to_uom_id', 'material_id'], { unique: true });
    await queryInterface.addIndex('uom_conversion', ['material_id']);
    await queryInterface.addIndex('uom_conversion', ['status']);
    await queryInterface.addIndex('uom_conversion', ['effective_from', 'effective_to']);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('uom_conversion');
  }
};

