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() {
        List<CouponTemplate> templates = templateService.getAvailableTemplates();
        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();
        IPage<UserCoupon> result = userCouponService.getMyCoupons(userId, status, page, pageSize);
        return Result.success("查询成功", PageResult.of(result));
    }

    @GetMapping("/{id}")
    public Result<UserCoupon> getCouponDetail(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        UserCoupon userCoupon = userCouponService.getDetail(id, userId);
        return Result.success("查询成功", userCoupon);
    }

    @PostMapping("/receive/{templateId}")
    public Result<UserCoupon> receiveCoupon(@PathVariable Long templateId) {
        Long userId = StpUtil.getLoginIdAsLong();
        UserCoupon userCoupon = userCouponService.receiveCoupon(userId, templateId);
        return Result.success("领取成功", userCoupon);
    }

    @GetMapping("/count")
    public Result<Map<String, Object>> getCouponCount() {
        Long userId = StpUtil.getLoginIdAsLong();
        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();
        List<UserCoupon> coupons = userCouponService.getAvailableCoupons(userId);
        return Result.success("查询成功", coupons);
    }
}
