'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('inventory_stock_adjustment', {
      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'
      },
      plant_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'plant',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT'
      },
      fiscal_year_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'fiscal_year',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT'
      },
      adjustment_number: {
        type: Sequelize.STRING(50),
        allowNull: false
      },
      adjustment_date: {
        type: Sequelize.DATEONLY,
        allowNull: false
      },
      adjustment_type: {
        type: Sequelize.ENUM('CYCLE_COUNT', 'PHYSICAL_INVENTORY', 'QUANTITY_ADJUSTMENT', 'VALUE_ADJUSTMENT'),
        allowNull: false,
        defaultValue: 'QUANTITY_ADJUSTMENT'
      },
      storage_location: {
        type: Sequelize.STRING(10),
        allowNull: true
      },
      status: {
        type: Sequelize.ENUM('DRAFT', 'POSTED', 'CANCELLED'),
        allowNull: false,
        defaultValue: 'DRAFT'
      },
      remarks: {
        type: Sequelize.TEXT,
        allowNull: true
      },
      posted_at: {
        type: Sequelize.DATE,
        allowNull: true
      },
      posted_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      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: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });

    await queryInterface.addIndex('inventory_stock_adjustment', ['company_id', 'plant_id', 'fiscal_year_id']);
    await queryInterface.addIndex('inventory_stock_adjustment', ['adjustment_number'], { unique: true });
    await queryInterface.addIndex('inventory_stock_adjustment', ['adjustment_date']);
    await queryInterface.addIndex('inventory_stock_adjustment', ['status']);
  },

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

