'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('route_card_operation_component_tracking', {
      id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
      route_card_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'route_card', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      route_card_operation_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'route_card_operation', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      material_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'material', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT',
      },
      required_quantity: { type: Sequelize.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      completed_quantity: { type: Sequelize.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      started_at: { type: Sequelize.DATE, allowNull: true },
      ended_at: { type: Sequelize.DATE, allowNull: true },
      total_minutes: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0 },
      created_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'user', key: 'id' },
      },
      updated_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'user', key: 'id' },
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
    });

    await queryInterface.addIndex(
      'route_card_operation_component_tracking',
      ['route_card_operation_id', 'material_id'],
      { unique: true, name: 'uq_rc_op_component' }
    );
    await queryInterface.addIndex(
      'route_card_operation_component_tracking',
      ['route_card_id'],
      { name: 'idx_rc_op_component_rc' }
    );
  },

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

