package com.izouma.nineth.service;

import com.izouma.nineth.config.Constants;
import com.izouma.nineth.domain.BlindBoxItem;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.PageWrapper;
import com.izouma.nineth.repo.BlindBoxItemRepo;
import com.izouma.nineth.utils.JpaUtils;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@AllArgsConstructor
public class BlindBoxItemService {

    private BlindBoxItemRepo blindBoxItemRepo;

    @Cacheable(value = "blindBoxList", key = "#pageQuery.hashCode()")
    public PageWrapper<BlindBoxItem> all(PageQuery pageQuery) {
        return PageWrapper.of(blindBoxItemRepo.findAll(JpaUtils.toSpecification(pageQuery, BlindBoxItem.class), JpaUtils.toPageRequest(pageQuery)));
    }

    @Cacheable(value = "blindBoxRare", key = "#blindBoxId")
    public HashMap<String, String> getBlindBoxRare(Long blindBoxId) {
        HashMap<String, String> rare = new HashMap<>();
        Map<String, BigDecimal> ssrMap = blindBoxItemRepo.getBlindBoxRare(blindBoxId, Constants.Rarity.SSR_LIKE, Constants.Rarity.U_LIKE);
        String ssr = convertToStr(ssrMap);
        if (StringUtil.isNotBlank(ssr)) {
            rare.put(Constants.Rarity.SSR, ssr);
        }
        Map<String, BigDecimal> srMap = blindBoxItemRepo.getBlindBoxRare(blindBoxId, Constants.Rarity.SR_LIKE, Constants.Rarity.SSR_LIKE);
        String sr = convertToStr(srMap);
        if (StringUtil.isNotBlank(sr)) {
            rare.put(Constants.Rarity.SR, sr);
        }
        Map<String, BigDecimal> uMap = blindBoxItemRepo.getBlindBoxRare(blindBoxId, Constants.Rarity.U_LIKE, Constants.Rarity.SR_LIKE);
        String u = convertToStr(uMap);
        if (StringUtil.isNotBlank(u)) {
            rare.put(Constants.Rarity.U, u);
        }
        return rare;
    }

    private String convertToStr(Map<String, BigDecimal> map) {
        if (map.containsKey("total") && Objects.nonNull(map.get("total"))) {
            if (map.containsKey("stock") && Objects.nonNull(map.get("stock"))) {
                return map.get("stock").toString().concat("/").concat(map.get("total").toString());
            }
            return "0/" + map.get("total").toString();
        }
        return null;
    }
}
