const commissionService = require('../services/commissionService');
const commissionConfigService = require('../services/commissionConfigService');

/**
 * Admin Commission Controller
 * Handles commission management for admin
 */

/**
 * Get all commissions
 * GET /api/v1/admin/commissions
 */
const getCommissions = async (req, res) => {
  try {
    const { page, limit, inviterId, inviteeId, status } = req.query;

    const result = await commissionService.getAllCommissions({
      page,
      limit,
      inviterId,
      inviteeId,
      status,
    });

    return res.status(200).json({
      code: 0,
      success: true,
      data: result,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'GET_COMMISSIONS_ERROR',
        message: 'Failed to get commissions',
        details: error.message,
      },
    });
  }
};

/**
 * Get commission statistics
 * GET /api/v1/admin/commissions/stats
 */
const getCommissionStats = async (req, res) => {
  try {
    const stats = await commissionService.getPlatformCommissionStats();

    return res.status(200).json({
      code: 0,
      success: true,
      data: stats,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'GET_STATS_ERROR',
        message: 'Failed to get commission statistics',
        details: error.message,
      },
    });
  }
};

/**
 * Get commission rate
 * GET /api/v1/admin/config/commission-rate
 */
const getCommissionRate = async (req, res) => {
  try {
    const config = await commissionConfigService.getCommissionRateConfig();

    return res.status(200).json({
      code: 0,
      success: true,
      data: config,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'GET_RATE_ERROR',
        message: 'Failed to get commission rate',
        details: error.message,
      },
    });
  }
};

/**
 * Set commission rate
 * PUT /api/v1/admin/config/commission-rate
 */
const setCommissionRate = async (req, res) => {
  try {
    const { rate } = req.body;

    if (rate === undefined || rate === null) {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'Rate is required',
        },
      });
    }

    const result = await commissionConfigService.setCommissionRate(rate);

    return res.status(200).json({
      code: 0,
      success: true,
      data: result,
      message: 'Commission rate updated successfully',
    });
  } catch (error) {
    if (error.message.includes('Invalid commission rate')) {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'INVALID_RATE',
          message: error.message,
        },
      });
    }

    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'SET_RATE_ERROR',
        message: 'Failed to set commission rate',
        details: error.message,
      },
    });
  }
};

/**
 * Get user's commission rate
 * GET /api/v1/admin/config/user-commission-rate/:userId
 */
const getUserCommissionRate = async (req, res) => {
  try {
    const { userId } = req.params;
    const rate = await commissionConfigService.getUserCommissionRate(userId);
    const systemRate = await commissionConfigService.getCommissionRate();

    // Get user info
    const User = require('../models/User');
    const user = await User.findByPk(userId, {
      attributes: ['id', 'uid', 'nickname', 'commissionRate'],
    });

    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        error: {
          code: 'USER_NOT_FOUND',
          message: 'User not found',
        },
      });
    }

    const hasCustomRate = user.commissionRate !== null && user.commissionRate !== undefined;

    return res.status(200).json({
      code: 0,
      success: true,
      data: {
        userId: user.id,
        uid: user.uid,
        nickname: user.nickname,
        commissionRate: rate,
        percentage: `${(rate * 100).toFixed(2)}%`,
        hasCustomRate,
        customRate: hasCustomRate ? parseFloat(user.commissionRate) : null,
        systemRate,
        systemPercentage: `${(systemRate * 100).toFixed(2)}%`,
      },
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'GET_USER_RATE_ERROR',
        message: 'Failed to get user commission rate',
        details: error.message,
      },
    });
  }
};

/**
 * Set user's commission rate
 * PUT /api/v1/admin/config/user-commission-rate/:userId
 */
const setUserCommissionRate = async (req, res) => {
  try {
    const { userId } = req.params;
    const { rate } = req.body;

    // rate can be null to clear custom rate
    const result = await commissionConfigService.setUserCommissionRate(userId, rate);

    return res.status(200).json({
      code: 0,
      success: true,
      data: result,
      message: rate === null || rate === '' 
        ? 'User commission rate cleared, will use system default' 
        : 'User commission rate updated successfully',
    });
  } catch (error) {
    if (error.message === 'User not found') {
      return res.status(404).json({
        code: 404,
        success: false,
        error: {
          code: 'USER_NOT_FOUND',
          message: 'User not found',
        },
      });
    }

    if (error.message.includes('Invalid commission rate')) {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'INVALID_RATE',
          message: error.message,
        },
      });
    }

    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'SET_USER_RATE_ERROR',
        message: 'Failed to set user commission rate',
        details: error.message,
      },
    });
  }
};

/**
 * Get all users with custom commission rates
 * GET /api/v1/admin/config/user-commission-rates
 */
const getUsersWithCustomRates = async (req, res) => {
  try {
    const users = await commissionConfigService.getUsersWithCustomRates();
    const systemRate = await commissionConfigService.getCommissionRate();

    return res.status(200).json({
      code: 0,
      success: true,
      data: {
        systemRate,
        systemPercentage: `${(systemRate * 100).toFixed(2)}%`,
        users,
        total: users.length,
      },
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'GET_CUSTOM_RATES_ERROR',
        message: 'Failed to get users with custom rates',
        details: error.message,
      },
    });
  }
};

module.exports = {
  getCommissions,
  getCommissionStats,
  getCommissionRate,
  setCommissionRate,
  getUserCommissionRate,
  setUserCommissionRate,
  getUsersWithCustomRates,
};
