package com.ycwl.basic.pricing.controller;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.pricing.dto.*;
import com.ycwl.basic.pricing.dto.resp.UserCouponResp;
import com.ycwl.basic.pricing.service.ICouponService;
import com.ycwl.basic.pricing.service.IPriceCalculationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 价格计算控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/pricing")
@RequiredArgsConstructor
public class PriceCalculationController {
    
    private final IPriceCalculationService priceCalculationService;
    private final ICouponService couponService;
    
    /**
     * 计算商品价格
     */
    @PostMapping("/calculate")
    public ApiResponse<PriceCalculationResult> calculatePrice(@RequestBody PriceCalculationRequest request) {
        log.info("价格计算请求: userId={}, products={}", request.getUserId(), request.getProducts().size());
        request.setPreviewOnly(true);
        PriceCalculationResult result = priceCalculationService.calculatePrice(request);
        
        log.info("价格计算完成: originalAmount={}, finalAmount={}, usedCoupon={}", 
                result.getOriginalAmount(), result.getFinalAmount(), 
                result.getUsedCoupon() != null ? result.getUsedCoupon().getCouponId() : null);
        
        return ApiResponse.success(result);
    }

    /**
     * 升单检测：判断是否命中一口价或打包优惠
     */
    @PostMapping("/upgrade-check")
    public ApiResponse<UpgradeCheckResult> upgradeCheck(@RequestBody UpgradeCheckRequest request) {
        log.info("升单检测请求: scenicId={}, purchased={}, intending={}",
                request.getScenicId(),
                request.getPurchasedProducts() != null ? request.getPurchasedProducts().size() : 0,
                request.getIntendingProducts() != null ? request.getIntendingProducts().size() : 0);
        
        UpgradeCheckResult result = priceCalculationService.checkUpgrade(request);
        return ApiResponse.success(result);
    }
    
    /**
     * 查询用户可用优惠券（包含领取记录信息）
     */
    @GetMapping("/coupons/my-coupons")
    public ApiResponse<List<UserCouponResp>> getUserCoupons(@RequestParam(required = false) String scenicId) {
        Long userId = getUserId();
        if (userId == null) {
            return ApiResponse.fail("用户未登录");
        }

        List<UserCouponResp> coupons = couponService.getUserAvailableCoupons(userId, scenicId);

        return ApiResponse.success(coupons);
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getUserId() {
        try {
            String userIdStr = BaseContextHandler.getUserId();
            if (userIdStr == null || userIdStr.isEmpty()) {
                return null;
            }
            return Long.valueOf(userIdStr);
        } catch (NumberFormatException e) {
            log.warn("无法解析用户ID: {}", BaseContextHandler.getUserId());
            return null;
        }
    }
}