package com.haha.miniapp.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.CouponTemplate;
import com.haha.entity.UserCoupon;
import com.haha.service.CouponTemplateService;
import com.haha.service.UserCouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping("/coupon")
@RequiredArgsConstructor
public class AppCouponController {

    private final CouponTemplateService templateService;
    private final UserCouponService userCouponService;

    @GetMapping("/available")
    public Result<List<CouponTemplate>> getAvailableCoupons() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[优惠券] 查询可领取优惠券列表 - userId: {}", userId);
        List<CouponTemplate> templates = templateService.getAvailableTemplatesWithStatus(userId);
        return Result.success("查询成功", templates);
    }

    @GetMapping("/my")
    public Result<PageResult<UserCoupon>> getMyCoupons(
            @RequestParam(defaultValue = "0") Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[优惠券] 查询用户优惠券列表 - userId: {}, status: {}, page: {}, pageSize: {}", 
                userId, status, page, pageSize);
        IPage<UserCoupon> result = userCouponService.getMyCoupons(userId, status, page, pageSize);
        log.info("[优惠券] 用户优惠券查询结果 - userId: {}, 总数: {}, 当前页数量: {}", 
                userId, result.getTotal(), result.getRecords().size());
        return Result.success("查询成功", PageResult.of(result));
    }

    @GetMapping("/{id}")
    public Result<UserCoupon> getCouponDetail(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[优惠券] 查询优惠券详情 - userId: {}, couponId: {}", userId, id);
        UserCoupon userCoupon = userCouponService.getDetail(id, userId);
        return Result.success("查询成功", userCoupon);
    }

    @PostMapping("/receive/{templateId}")
    public Result<UserCoupon> receiveCoupon(@PathVariable Long templateId) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[优惠券] 领取优惠券 - userId: {}, templateId: {}", userId, templateId);
        try {
            UserCoupon userCoupon = userCouponService.receiveCoupon(userId, templateId);
            log.info("[优惠券] 领取成功 - userId: {}, templateId: {}, couponCode: {}", 
                    userId, templateId, userCoupon.getCouponCode());
            return Result.success("领取成功", userCoupon);
        } catch (Exception e) {
            log.warn("[优惠券] 领取失败 - userId: {}, templateId: {}, reason: {}", 
                    userId, templateId, e.getMessage());
            throw e;
        }
    }

    @GetMapping("/count")
    public Result<Map<String, Object>> getCouponCount() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.debug("[优惠券] 查询用户可用优惠券数量 - userId: {}", userId);
        int availableCount = userCouponService.countAvailableCoupons(userId);

        Map<String, Object> result = new HashMap<>();
        result.put("availableCount", availableCount);

        return Result.success("查询成功", result);
    }

    @GetMapping("/usable")
    public Result<List<UserCoupon>> getUsableCoupons() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[优惠券] 查询用户可用优惠券 - userId: {}", userId);
        List<UserCoupon> coupons = userCouponService.getAvailableCoupons(userId);
        log.info("[优惠券] 用户可用优惠券数量 - userId: {}, count: {}", userId, coupons.size());
        return Result.success("查询成功", coupons);
    }
}
