const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

/**
 * Commission Model
 * Represents commission records for invitation rewards
 */
const Commission = sequelize.define('Commission', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  inviterId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'inviter_id',
    references: {
      model: 'user',
      key: 'id',
    },
    comment: '邀请者ID（获得佣金的用户）',
  },
  inviteeId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'invitee_id',
    references: {
      model: 'user',
      key: 'id',
    },
    comment: '被邀请者ID（支付的用户）',
  },
  paymentOrderId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'payment_order_id',
    references: {
      model: 'payment_orders',
      key: 'id',
    },
    comment: '关联的支付订单ID',
  },
  paymentAmount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    field: 'payment_amount',
    comment: '支付金额',
  },
  commissionRate: {
    type: DataTypes.DECIMAL(5, 4),
    allowNull: false,
    field: 'commission_rate',
    comment: '使用的佣金比例（如0.02表示2%）',
  },
  commissionAmount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    field: 'commission_amount',
    comment: '佣金金额',
  },
  status: {
    type: DataTypes.ENUM('credited', 'cancelled'),
    defaultValue: 'credited',
    allowNull: false,
    comment: '佣金状态',
  },
}, {
  tableName: 'commissions',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['inviter_id'] },
    { fields: ['invitee_id'] },
    { fields: ['payment_order_id'] },
    { fields: ['status'] },
    { fields: ['created_at'] },
  ],
});

module.exports = Commission;
