'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('production_nesting_confirmation_component', {
      id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
      company_id: { type: Sequelize.INTEGER, allowNull: false },
      production_order_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'production_order', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      confirmation_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'production_nesting_confirmation', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      production_order_component_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'production_order_component', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      material_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'material', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT'
      },
      created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex(
      'production_nesting_confirmation_component',
      ['confirmation_id'],
      { name: 'idx_pncc_confirmation' }
    );
    await queryInterface.addIndex(
      'production_nesting_confirmation_component',
      ['production_order_id'],
      { name: 'idx_pncc_po' }
    );
    await queryInterface.addIndex(
      'production_nesting_confirmation_component',
      ['confirmation_id', 'production_order_component_id'],
      { unique: true, name: 'uq_pncc_confirmation_component' }
    );
  },

  down: async (queryInterface) => {
    await queryInterface.dropTable('production_nesting_confirmation_component');
  }
};

