package com.ycwl.basic.pricing.controller;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.pricing.dto.CouponClaimResult;
import com.ycwl.basic.pricing.dto.req.SceneCouponClaimReq;
import com.ycwl.basic.pricing.dto.resp.SceneCouponAvailableResp;
import com.ycwl.basic.pricing.service.ISceneCouponService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 场景优惠券领取控制器（前端/移动端）
 */
@Slf4j
@RestController
@RequestMapping("/api/pricing/scene-coupon")
@RequiredArgsConstructor
public class SceneCouponClaimController {

    private final ISceneCouponService sceneCouponService;

    /**
     * 查询场景下可领取的优惠券列表
     *
     * @param sceneKey 场景标识
     * @param scenicId 景区ID
     * @return 可领取优惠券列表（包含用户领取状态）
     */
    @GetMapping("/available")
    public ApiResponse<List<SceneCouponAvailableResp>> getAvailableCoupons(
            @RequestParam String sceneKey,
            @RequestParam Long scenicId) {
        try {
            Long userId = getUserId();
            List<SceneCouponAvailableResp> list = sceneCouponService.getAvailableCoupons(sceneKey, scenicId, userId);
            return ApiResponse.success(list);
        } catch (Exception e) {
            log.error("场景优惠券|可领取列表查询失败 sceneKey={}, scenicId={}", sceneKey, scenicId, e);
            return ApiResponse.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 领取场景优惠券
     *
     * @param req 领取请求
     * @return 领取结果列表
     */
    @PostMapping("/claim")
    public ApiResponse<List<CouponClaimResult>> claimCoupons(@RequestBody SceneCouponClaimReq req) {
        try {
            Long userId = getUserId();
            if (userId == null) {
                return ApiResponse.fail("用户未登录");
            }

            List<CouponClaimResult> results = sceneCouponService.claimCoupons(req, userId);

            // 无论成功或失败，都返回完整结果列表（包含已领取的券信息）
            return ApiResponse.success(results);
        } catch (Exception e) {
            log.error("场景优惠券|领取失败 req={}", req, e);
            return ApiResponse.fail("领取失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户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;
        }
    }
}
