module.exports = (sequelize, DataTypes) => {
  const PurchaseCosting = sequelize.define('PurchaseCosting', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    vendor_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'BusinessPartner',
        key: 'id'
      }
    },
    po_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'PurchaseOrder',
        key: 'id'
      }
    },
    purchase_costing_number: {
      type: DataTypes.STRING(80),
      allowNull: true
    },
    rate: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    previous_rate: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: true
    },
    difference: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: true
    },
    percentage: {
      type: DataTypes.DECIMAL(10, 4),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('NORMAL', 'WARNING', 'CRITICAL'),
      allowNull: false,
      defaultValue: 'NORMAL'
    },
    reason: {
      type: DataTypes.STRING(300),
      allowNull: true
    },
    approval_status: {
      type: DataTypes.ENUM('NOT_REQUIRED', 'PENDING', 'APPROVED', 'REJECTED'),
      allowNull: false,
      defaultValue: 'NOT_REQUIRED'
    },
    created_date: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    }
  }, {
    tableName: 'purchase_costing',
    indexes: [
      { fields: ['material_id', 'date'] },
      { fields: ['vendor_id', 'date'] },
      { fields: ['po_id'] },
      { fields: ['purchase_costing_number'], unique: true },
      { fields: ['status'] },
      { fields: ['approval_status'] }
    ]
  });

  PurchaseCosting.associate = function(models) {
    PurchaseCosting.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    PurchaseCosting.belongsTo(models.BusinessPartner, { foreignKey: 'vendor_id', as: 'vendor' });
    PurchaseCosting.belongsTo(models.PurchaseOrder, { foreignKey: 'po_id', as: 'purchaseOrder' });
  };

  return PurchaseCosting;
};
