module.exports = (sequelize, DataTypes) => {
  const ProductionOrderBatch = sequelize.define(
    'ProductionOrderBatch',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      production_order_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'ProductionOrder',
          key: 'id'
        }
      },
      batch_sequence: {
        type: DataTypes.INTEGER,
        allowNull: false
      },
      batch_label: {
        type: DataTypes.STRING(50),
        allowNull: true
      },
      quantity: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false
      },
      planned_start_date: {
        type: DataTypes.DATEONLY,
        allowNull: true
      },
      planned_finish_date: {
        type: DataTypes.DATEONLY,
        allowNull: true
      },
      status: {
        type: DataTypes.ENUM('PLANNED', 'RELEASED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED'),
        allowNull: false,
        defaultValue: 'PLANNED'
      },
      released_at: {
        type: DataTypes.DATE,
        allowNull: true
      },
      released_by: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
          model: 'User',
          key: 'id'
        }
      },
      remarks: {
        type: DataTypes.TEXT,
        allowNull: true
      }
    },
    {
      tableName: 'production_order_batch',
      indexes: [
        { fields: ['production_order_id'] },
        { unique: true, fields: ['production_order_id', 'batch_sequence'] },
        { fields: ['status'] }
      ]
    }
  );

  ProductionOrderBatch.associate = function (models) {
    ProductionOrderBatch.belongsTo(models.ProductionOrder, {
      foreignKey: 'production_order_id',
      as: 'productionOrder'
    });
    ProductionOrderBatch.belongsTo(models.User, { foreignKey: 'released_by', as: 'releasedByUser' });
  };

  return ProductionOrderBatch;
};
