module.exports = (sequelize, DataTypes) => {
  const SubcontractDCItem = sequelize.define('SubcontractDCItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    subcontract_dc_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SubcontractDC', key: 'id' }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Material', key: 'id' }
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    sent_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    unit_price: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    line_total: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    received_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    rejection_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'UOM', key: 'id' }
    },
    storage_location_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'StorageLocation', key: 'id' }
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'subcontract_dc_item',
    indexes: [
      { fields: ['subcontract_dc_id'] },
      { fields: ['material_id'] },
      { fields: ['uom_id'] },
      { fields: ['storage_location_id'] },
      { unique: true, fields: ['subcontract_dc_id', 'line_number'] }
    ]
  });

  SubcontractDCItem.associate = function(models) {
    SubcontractDCItem.belongsTo(models.SubcontractDC, { foreignKey: 'subcontract_dc_id', as: 'subcontractDC' });
    SubcontractDCItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    SubcontractDCItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
    SubcontractDCItem.belongsTo(models.StorageLocation, { foreignKey: 'storage_location_id', as: 'storageLocation' });
    SubcontractDCItem.hasMany(models.SubcontractReceiptItem, { foreignKey: 'subcontract_dc_item_id', as: 'receiptItems' });
  };

  return SubcontractDCItem;
};
