const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Referral = sequelize.define('Referral', {
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
    },
    referrerId: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      field: 'referrer_id',
      references: {
        model: 'users',
        key: 'id',
      },
    },
    referredId: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      unique: true,
      field: 'referred_id',
      references: {
        model: 'users',
        key: 'id',
      },
    },
    status: {
      type: DataTypes.ENUM('pending', 'active', 'inactive'),
      defaultValue: 'pending',
    },
    totalEarnings: {
      type: DataTypes.DECIMAL(20, 8),
      defaultValue: 0,
      field: 'total_earnings',
    },
    totalTradingVolume: {
      type: DataTypes.DECIMAL(30, 8),
      defaultValue: 0,
      field: 'total_trading_volume',
    },
    commissionRate: {
      type: DataTypes.DECIMAL(10, 4),
      field: 'commission_rate',
    },
    activatedAt: {
      type: DataTypes.DATE,
      field: 'activated_at',
    },
    lastEarningAt: {
      type: DataTypes.DATE,
      field: 'last_earning_at',
    },
    metadata: {
      type: DataTypes.JSON,
      defaultValue: {},
    },
  }, {
    tableName: 'referrals',
    timestamps: true,
    underscored: true,
    indexes: [
      { fields: ['referrer_id'] },
      { fields: ['referred_id'] },
      { fields: ['status'] },
    ],
  });



  return Referral;
};
