module.exports = (sequelize, DataTypes) => {
  const DeliveryChallanItem = sequelize.define('DeliveryChallanItem', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    delivery_challan_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'DeliveryChallan', key: 'id', onDelete: 'CASCADE' }
    },
    item_number: { type: DataTypes.INTEGER, allowNull: false },
    invoice_item_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'SalesInvoiceItem', key: 'id' }
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Material', key: 'id' }
    },
    item_code: { type: DataTypes.STRING(60), allowNull: true },
    item_name: { type: DataTypes.STRING(300), allowNull: true },
    hsn_code: { type: DataTypes.STRING(20), allowNull: true },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'UOM', key: 'id' }
    },
    order_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
    invoice_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
    dispatch_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
    delivered_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
    remarks: { type: DataTypes.TEXT, allowNull: true }
  }, {
    tableName: 'delivery_challan_item',
    indexes: [
      { fields: ['delivery_challan_id'] },
      { fields: ['material_id'] },
      { fields: ['invoice_item_id'] }
    ]
  });

  DeliveryChallanItem.associate = function(models) {
    DeliveryChallanItem.belongsTo(models.DeliveryChallan, { foreignKey: 'delivery_challan_id', as: 'deliveryChallan' });
    DeliveryChallanItem.belongsTo(models.SalesInvoiceItem, { foreignKey: 'invoice_item_id', as: 'invoiceItem' });
    DeliveryChallanItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    DeliveryChallanItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
  };

  return DeliveryChallanItem;
};

