'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('material_group', {
      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'
      },
      group_code: {
        type: Sequelize.STRING(20),
        allowNull: false,
        comment: 'Unique code for material group (e.g., CABINET, ASSEMBLY, PARTS)'
      },
      group_name: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: 'Name of material group (e.g., Cabinet, Assembly, Parts)'
      },
      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_group', ['company_id', 'group_code'], { 
      unique: true, 
      name: 'material_group_uniq_key' 
    });
    await queryInterface.addIndex('material_group', ['company_id']);
    await queryInterface.addIndex('material_group', ['is_active']);
  },

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

