'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('material_type', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      company_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'company',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT'
      },
      type_code: {
        type: Sequelize.STRING(20),
        allowNull: false,
        comment: 'Unique code for material type (e.g., RAW_MAT, SEMI_FIN, FIN_GOOD)'
      },
      type_name: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: 'Name of material type (e.g., Raw Material, Semi-Finished Good)'
      },
      description: {
        type: Sequelize.STRING(500),
        allowNull: true
      },
      is_active: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: 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('material_type', ['company_id', 'type_code'], { 
      unique: true, 
      name: 'material_type_uniq_key' 
    });
    await queryInterface.addIndex('material_type', ['company_id']);
    await queryInterface.addIndex('material_type', ['is_active']);
  },

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

