'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('storage_location', {
      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'
      },
      storage_location_code: {
        type: Sequelize.STRING(10),
        allowNull: false
      },
      description: {
        type: Sequelize.STRING(200),
        allowNull: false
      },
      storage_location_type: {
        type: Sequelize.ENUM('WAREHOUSE', 'PRODUCTION', 'QUALITY', 'SCRAP', 'BLOCKED', 'OTHER'),
        allowNull: true,
        defaultValue: 'WAREHOUSE'
      },
      address: {
        type: Sequelize.STRING(500),
        allowNull: true
      },
      status: {
        type: Sequelize.ENUM('ACTIVE', 'INACTIVE', 'BLOCKED'),
        allowNull: false,
        defaultValue: 'ACTIVE'
      },
      effective_from: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      effective_to: {
        type: Sequelize.DATEONLY,
        allowNull: 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('storage_location', ['company_id', 'plant_id', 'storage_location_code'], { unique: true });
    await queryInterface.addIndex('storage_location', ['plant_id']);
    await queryInterface.addIndex('storage_location', ['status']);
  },

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

