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

/**
 * Admin Payment Order Controller
 * Handles payment order management for admin
 */

/**
 * Create payment order
 * POST /api/v1/admin/payment-orders
 */
const createPaymentOrder = async (req, res) => {
  try {
    const adminId = req.adminId || req.admin?.id;
    const { userId, appointmentId, amount, amountPeso, amountRmb, serviceContent, paymentTime, notes } = req.body;

    const result = await paymentOrderService.createPaymentOrder({
      userId: userId ? userId.trim() : userId, // Trim whitespace
      appointmentId,
      amount,
      amountPeso,
      amountRmb,
      serviceContent,
      paymentTime,
      notes,
    }, adminId);

    return res.status(201).json({
      code: 0,
      success: true,
      data: result,
      message: 'Payment order created successfully',
    });
  } catch (error) {
    if (error.message.includes('请') || error.message.includes('不存在')) {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: error.message,
        },
      });
    }

    console.error('Create payment order error:', error);
    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'CREATE_ORDER_ERROR',
        message: '创建支付订单失败',
        details: error.message,
      },
    });
  }
};

/**
 * Get payment orders
 * GET /api/v1/admin/payment-orders
 */
const getPaymentOrders = async (req, res) => {
  try {
    const { page, limit, userId, status, startDate, endDate, search, currency } = req.query;

    const result = await paymentOrderService.getPaymentOrders({
      page,
      limit,
      userId,
      status,
      startDate,
      endDate,
      search,
      currency,
    });

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

/**
 * Get payment order by ID
 * GET /api/v1/admin/payment-orders/:id
 */
const getPaymentOrderById = async (req, res) => {
  try {
    const { id } = req.params;

    const order = await paymentOrderService.getPaymentOrderById(id);

    return res.status(200).json({
      code: 0,
      success: true,
      data: order,
    });
  } catch (error) {
    if (error.message === 'Payment order not found') {
      return res.status(404).json({
        code: 404,
        success: false,
        error: {
          code: 'ORDER_NOT_FOUND',
          message: 'Payment order not found',
        },
      });
    }

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

/**
 * Cancel payment order
 * PUT /api/v1/admin/payment-orders/:id/cancel
 */
const cancelPaymentOrder = async (req, res) => {
  try {
    const { id } = req.params;
    const { cancelReason } = req.body;

    const result = await paymentOrderService.cancelPaymentOrder(id, cancelReason);

    return res.status(200).json({
      code: 0,
      success: true,
      data: result,
      message: 'Payment order cancelled successfully',
    });
  } catch (error) {
    if (error.message === 'Payment order not found') {
      return res.status(404).json({
        code: 404,
        success: false,
        error: {
          code: 'ORDER_NOT_FOUND',
          message: 'Payment order not found',
        },
      });
    }

    if (error.message === 'Payment order is already cancelled') {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'ALREADY_CANCELLED',
          message: 'Payment order is already cancelled',
        },
      });
    }

    if (error.message.includes('请')) {
      return res.status(400).json({
        code: 400,
        success: false,
        error: {
          code: 'INVALID_INPUT',
          message: error.message,
        },
      });
    }

    return res.status(500).json({
      code: 500,
      success: false,
      error: {
        code: 'CANCEL_ORDER_ERROR',
        message: 'Failed to cancel payment order',
        details: error.message,
      },
    });
  }
};

module.exports = {
  createPaymentOrder,
  getPaymentOrders,
  getPaymentOrderById,
  cancelPaymentOrder,
};
