package cn.reghao.tnb.content.app.mall.db.repository;

import cn.reghao.tnb.content.api.dto.ItemSnapshot;
import cn.reghao.tnb.content.app.mall.db.mapper.ProductMapper;
import cn.reghao.tnb.content.app.mall.db.mapper.ProductSnapshotMapper;
import cn.reghao.tnb.content.app.mall.model.po.Product;
import cn.reghao.tnb.content.app.mall.model.po.ProductSnapshot;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author reghao
 * @date 2024-04-16 15:27:35
 */
@Slf4j
@Repository
public class MallRepository {
    private final ProductMapper productMapper;
    private final ProductSnapshotMapper productSnapshotMapper;

    public MallRepository(ProductMapper productMapper, ProductSnapshotMapper productSnapshotMapper) {
        this.productMapper = productMapper;
        this.productSnapshotMapper = productSnapshotMapper;
    }

    // TODO 需要锁来保证库存变化的准确性
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(int amount, ProductSnapshot productSnapshot) {
        long productId = productSnapshot.getItemId();
        // 减商品库存
        productMapper.updateStockMinus(productId, amount);
        productSnapshotMapper.save(productSnapshot);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCancelOrder(long productId, int amount) {
        // 恢复商品库存
        productMapper.updateStockMinus(productId, amount);
    }

    //@Cacheable(cacheNames = "tnb:mall:product", key = "#itemId", unless = "#result == null")
    public Product getProduct(Long itemId) {
        log.info("miss cache");
        return productMapper.findByItemId(itemId);
    }

    public ItemSnapshot getItemSnapshot(long orderId) {
        return productSnapshotMapper.findItemSnapshotByOrderId(orderId);
    }
}
