const Config = require('../models/Config');

/**
 * Commission Config Service
 * Handles commission rate configuration
 */

// Default commission rate (2%)
const DEFAULT_COMMISSION_RATE = 0.02;
const COMMISSION_RATE_KEY = 'commission_rate';

/**
 * Get current commission rate
 * @returns {number} Commission rate (e.g., 0.02 for 2%)
 */
const getCommissionRate = async () => {
  const config = await Config.findOne({
    where: { key: COMMISSION_RATE_KEY },
  });

  if (!config) {
    return DEFAULT_COMMISSION_RATE;
  }

  const rate = parseFloat(config.value);
  if (isNaN(rate) || rate < 0 || rate > 1) {
    return DEFAULT_COMMISSION_RATE;
  }

  return rate;
};

/**
 * Set commission rate
 * @param {number} rate - Commission rate (e.g., 0.02 for 2%)
 * @returns {Object} Updated config
 */
const setCommissionRate = async (rate) => {
  // Validate rate
  const rateValue = parseFloat(rate);
  if (isNaN(rateValue) || rateValue < 0 || rateValue > 1) {
    throw new Error('Invalid commission rate. Must be between 0 and 1.');
  }

  // Find or create config
  let config = await Config.findOne({
    where: { key: COMMISSION_RATE_KEY },
  });

  if (config) {
    config.value = rateValue.toString();
    await config.save();
  } else {
    config = await Config.create({
      key: COMMISSION_RATE_KEY,
      value: rateValue.toString(),
      type: 'number',
      category: 'invitation',
      description: '邀请佣金比例（如0.02表示2%）',
    });
  }

  return {
    key: config.key,
    value: rateValue,
    updatedAt: config.updatedAt,
  };
};

/**
 * Get commission rate config details
 * @returns {Object} Config details
 */
const getCommissionRateConfig = async () => {
  const config = await Config.findOne({
    where: { key: COMMISSION_RATE_KEY },
  });

  const rate = config ? parseFloat(config.value) : DEFAULT_COMMISSION_RATE;

  return {
    key: COMMISSION_RATE_KEY,
    value: rate,
    percentage: `${(rate * 100).toFixed(2)}%`,
    isDefault: !config,
    updatedAt: config ? config.updatedAt : null,
  };
};

module.exports = {
  getCommissionRate,
  setCommissionRate,
  getCommissionRateConfig,
  DEFAULT_COMMISSION_RATE,
  COMMISSION_RATE_KEY,
};
