module.exports = (sequelize, DataTypes) => {
  const ProductionOrderMaterialReceiptLine = sequelize.define(
    'ProductionOrderMaterialReceiptLine',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      production_order_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'ProductionOrder', key: 'id' },
      },
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'Company', key: 'id' },
      },
      plant_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'Plant', key: 'id' },
      },
      line_type: {
        type: DataTypes.STRING(20),
        allowNull: false,
      },
      line_key: {
        type: DataTypes.STRING(160),
        allowNull: false,
      },
      material_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'Material', key: 'id' },
      },
      material_name: {
        type: DataTypes.STRING(500),
        allowNull: true,
      },
      received_qty: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0,
      },
      from_storage_location_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'StorageLocation', key: 'id' },
      },
      to_storage_location_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'StorageLocation', key: 'id' },
      },
      received_date: {
        type: DataTypes.DATEONLY,
        allowNull: true,
      },
    },
    {
      tableName: 'production_order_material_receipt_line',
      underscored: true,
      indexes: [
        { fields: ['production_order_id'] },
        { unique: true, fields: ['production_order_id', 'line_type', 'line_key'] },
      ],
    }
  );

  ProductionOrderMaterialReceiptLine.associate = (models) => {
    ProductionOrderMaterialReceiptLine.belongsTo(models.ProductionOrder, {
      foreignKey: 'production_order_id',
      as: 'productionOrder',
    });
    ProductionOrderMaterialReceiptLine.belongsTo(models.StorageLocation, {
      foreignKey: 'from_storage_location_id',
      as: 'fromStorageLocation',
    });
    ProductionOrderMaterialReceiptLine.belongsTo(models.StorageLocation, {
      foreignKey: 'to_storage_location_id',
      as: 'toStorageLocation',
    });
    ProductionOrderMaterialReceiptLine.belongsTo(models.Material, {
      foreignKey: 'material_id',
      as: 'material',
    });
  };

  return ProductionOrderMaterialReceiptLine;
};
