const withdrawalService = require('../services/withdrawalService');

/**
 * Withdrawal Controller
 * Handles withdrawal-related HTTP requests
 */

/**
 * Create withdrawal request
 * POST /api/v1/withdrawals
 */
const createWithdrawal = async (req, res) => {
  try {
    const userId = req.user.id;
    const { amount, paymentMethod, paymentDetails } = req.body;

    // Validate required fields
    if (!amount || !paymentMethod || !paymentDetails) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: 'Amount, payment method, and payment details are required',
        },
      });
    }

    const withdrawal = await withdrawalService.createWithdrawal(userId, {
      amount,
      paymentMethod,
      paymentDetails,
    });

    return res.status(201).json({
      success: true,
      data: {
        id: withdrawal.id,
        withdrawalNo: withdrawal.withdrawalNo,
        amount: parseFloat(withdrawal.amount).toFixed(2),
        paymentMethod: withdrawal.paymentMethod,
        status: withdrawal.status,
        createdAt: withdrawal.createdAt,
      },
    });
  } catch (error) {
    // Handle specific errors
    if (error.message.includes('Minimum withdrawal amount')) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'AMOUNT_TOO_LOW',
          message: error.message,
        },
      });
    }

    if (error.message === 'Insufficient balance') {
      return res.status(400).json({
        success: false,
        error: {
          code: 'INSUFFICIENT_BALANCE',
          message: 'Insufficient balance for withdrawal',
        },
      });
    }

    if (error.message === 'Invalid payment method') {
      return res.status(400).json({
        success: false,
        error: {
          code: 'INVALID_PAYMENT_METHOD',
          message: 'Payment method must be wechat, alipay, or bank',
        },
      });
    }

    return res.status(500).json({
      success: false,
      error: {
        code: 'CREATE_WITHDRAWAL_ERROR',
        message: 'Failed to create withdrawal request',
        details: error.message,
      },
    });
  }
};

/**
 * Get withdrawal records
 * GET /api/v1/withdrawals
 */
const getWithdrawals = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page, limit, status } = req.query;

    const result = await withdrawalService.getWithdrawals(userId, {
      page,
      limit,
      status,
    });

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

/**
 * Get withdrawal details
 * GET /api/v1/withdrawals/:id
 */
const getWithdrawalById = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;

    const withdrawal = await withdrawalService.getWithdrawalById(userId, id);

    return res.status(200).json({
      success: true,
      data: withdrawal,
    });
  } catch (error) {
    if (error.message === 'Withdrawal not found') {
      return res.status(404).json({
        success: false,
        error: {
          code: 'WITHDRAWAL_NOT_FOUND',
          message: 'Withdrawal not found',
        },
      });
    }

    return res.status(500).json({
      success: false,
      error: {
        code: 'GET_WITHDRAWAL_ERROR',
        message: 'Failed to get withdrawal details',
        details: error.message,
      },
    });
  }
};

module.exports = {
  createWithdrawal,
  getWithdrawals,
  getWithdrawalById,
};
