'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('production_order_material_receipt_line', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      production_order_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'production_order', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      company_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'company', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT',
      },
      plant_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'plant', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT',
      },
      line_type: {
        type: Sequelize.STRING(20),
        allowNull: false,
        comment: 'RAW | FASTENER',
      },
      line_key: {
        type: Sequelize.STRING(160),
        allowNull: false,
        comment: 'RAW: sheet group id; FASTENER: material_id',
      },
      material_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'material', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      material_name: {
        type: Sequelize.STRING(500),
        allowNull: true,
      },
      received_qty: {
        type: Sequelize.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0,
      },
      from_storage_location_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'storage_location', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      to_storage_location_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'storage_location', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      received_date: {
        type: Sequelize.DATEONLY,
        allowNull: true,
      },
      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_order_material_receipt_line', ['production_order_id'], {
      name: 'po_mrl_po_id_idx',
    });
    await queryInterface.addIndex(
      'production_order_material_receipt_line',
      ['production_order_id', 'line_type', 'line_key'],
      {
        unique: true,
        name: 'po_mrl_po_type_key_uniq',
      }
    );
  },

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