package cn.reghao.tnb.content.app.mall.service;

import cn.reghao.tnb.content.app.mall.db.repository.MallRepository;
import cn.reghao.tnb.content.app.mall.model.po.Product;
import cn.reghao.tnb.content.app.mall.model.vo.CartCard;
import cn.reghao.tnb.content.app.util.redis.ds.RedisHash;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-04-15 15:00:10
 */
@Service
public class CartService {
    private final String cartKeyPrefix = "tnb:mall:cart";
    private final RedisHash<String> redisHash;
    private final MallRepository mallRepository;

    public CartService(RedisHash<String> redisHash, MallRepository mallRepository) {
        this.redisHash = redisHash;
        this.mallRepository = mallRepository;
    }

    public void addCartItem(long userId, long productId, int num) {
        String key = String.format("%s:%s", cartKeyPrefix, userId);
        String productIdStr = String.valueOf(productId);
        redisHash.hset(key, productIdStr, num+"");
    }

    public void deleteCartItem(long userId, long productId) {
        String key = String.format("%s:%s", cartKeyPrefix, userId);
        String productIdStr = String.valueOf(productId);
        redisHash.hdel(key, productIdStr);
    }

    public List<CartCard> getUserCart(long userId) {
        String key = String.format("%s:%s", cartKeyPrefix, userId);
        Long total = redisHash.hlen(key);
        Map<String, String> items = redisHash.hgetall(key);

        List<CartCard> list = new ArrayList<>();
        items.forEach((itemId, num) -> {
            Product product = mallRepository.getProduct(Long.parseLong(itemId));
            if (product != null) {
                list.add(new CartCard(product, Integer.parseInt(num)));
            }
        });

        return list;
    }
}
