package com.zhentao.controller;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.zhentao.common.Result;
import com.zhentao.dto.CoursePurchaseRequest;
import com.zhentao.entity.Course;
import com.zhentao.service.CourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 课程订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/course-order")
public class CourseOrderController {

    @Autowired
    private CourseOrderService courseOrderService;

    /**
     * 购买课程（获取支付参数）
     */
    @PostMapping("/purchase")
    public Result<Map<String, Object>> purchaseCourse(@RequestBody CoursePurchaseRequest request) {
        try {
            Map<String, Object> payParams = courseOrderService.purchaseCourse(
                    request.getUserId(),
                    request.getCourseId(),
                    request.getCourseName(),
                    request.getPrice()
            );
            return Result.success(payParams);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (WxPayException e) {
            log.error("微信支付下单失败", e);
            return Result.error("支付下单失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("课程购买失败", e);
            return Result.error("课程购买失败");
        }
    }

    /**
     * 微信支付回调
     */
    @PostMapping("/notify")
    public String handlePayNotify(@RequestBody String notifyData) {
        log.info("收到课程支付回调：{}", notifyData);
        try {
            return courseOrderService.handlePayNotify(notifyData);
        } catch (WxPayException e) {
            log.error("处理课程支付回调失败", e);
            return "处理支付回调失败";
        }
    }

    /**
     * 检查用户是否已购买课程
     */
    @GetMapping("/check")
    public Result<Boolean> checkPurchased(
            @RequestParam Long userId,
            @RequestParam Integer courseId) {
        try {
            boolean purchased = courseOrderService.checkPurchased(userId, courseId);
            return Result.success(purchased);
        } catch (Exception e) {
            log.error("检查购买状态失败", e);
            return Result.error("检查购买状态失败");
        }
    }

    /**
     * 获取用户已购买的课程ID列表
     */
    @GetMapping("/purchased")
    public Result<List<Course>> getPurchasedCourses(@RequestParam Long userId) {
        try {
            List<Course> courseIds = courseOrderService.getPurchasedCourseIds(userId);
            return Result.success(courseIds);
        } catch (Exception e) {
            log.error("获取已购买课程失败", e);
            return Result.error("获取已购买课程失败");
        }
    }
}
