module.exports = (sequelize, DataTypes) => {
  const SubcontractReceipt = sequelize.define('SubcontractReceipt', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Company', key: 'id' }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Plant', key: 'id' }
    },
    fiscal_year_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'FiscalYear', key: 'id' }
    },
    receipt_number: {
      type: DataTypes.STRING(50),
      allowNull: false
    },
    receipt_date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    vendor_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'BusinessPartner', key: 'id' }
    },
    subcontract_dc_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SubcontractDC', key: 'id' }
    },
    total_received_qty: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    total_rejection_qty: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('POSTED', 'CANCELLED'),
      allowNull: false,
      defaultValue: 'POSTED'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'User', key: 'id' }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'User', key: 'id' }
    }
  }, {
    tableName: 'subcontract_receipt',
    indexes: [
      { fields: ['company_id', 'plant_id', 'fiscal_year_id'] },
      { unique: true, fields: ['company_id', 'receipt_number'] },
      { fields: ['vendor_id'] },
      { fields: ['subcontract_dc_id'] },
      { fields: ['receipt_date'] }
    ]
  });

  SubcontractReceipt.associate = function(models) {
    SubcontractReceipt.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    SubcontractReceipt.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    SubcontractReceipt.belongsTo(models.FiscalYear, { foreignKey: 'fiscal_year_id', as: 'fiscalYear' });
    SubcontractReceipt.belongsTo(models.BusinessPartner, { foreignKey: 'vendor_id', as: 'vendor' });
    SubcontractReceipt.belongsTo(models.SubcontractDC, { foreignKey: 'subcontract_dc_id', as: 'subcontractDC' });
    SubcontractReceipt.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    SubcontractReceipt.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
    SubcontractReceipt.hasMany(models.SubcontractReceiptItem, { foreignKey: 'subcontract_receipt_id', as: 'items' });
  };

  return SubcontractReceipt;
};
