package com.izouma.nineth.service;

import com.izouma.nineth.domain.RockRecord;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.repo.RockRecordRepo;
import com.izouma.nineth.repo.TokenHistoryRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@AllArgsConstructor
public class RockRecordService {

    private RockRecordRepo   rockRecordRepo;
    private TokenHistoryRepo tokenHistoryRepo;

    public Page<RockRecord> all(PageQuery pageQuery) {
        return rockRecordRepo.findAll(JpaUtils.toSpecification(pageQuery, RockRecord.class), JpaUtils.toPageRequest(pageQuery));
    }

    public RockRecord getRock(Long userId) {
        RockRecord rockRecord = rockRecordRepo.findFirstByUserIdOrderByIdDesc(userId);
        if (rockRecord != null) {
            return rockRecord;
        }
        BigDecimal amount = tokenHistoryRepo.userBuy(userId);
        if (amount == null) {
            return rockRecordRepo.saveAndFlush(RockRecord.builder()
                    .lastRecord(BigDecimal.ZERO)
                    .amount(BigDecimal.ZERO)
                    .operation("初始")
                    .userId(userId)
                    .record(BigDecimal.ZERO)
                    .build());
        }
        return rockRecordRepo.saveAndFlush(RockRecord.builder()
                .lastRecord(BigDecimal.ZERO)
                .operation("购买")
                .amount(amount)
                .userId(userId)
                .record(amount)
                .build());
    }

    @CacheEvict(value = "userStat", key = "#userId")
    public void addRock(Long userId, BigDecimal amount, String operation) {
        RockRecord rock = this.getRock(userId);
        rockRecordRepo.save(RockRecord.builder()
                .lastRecord(rock.getRecord())
                .operation(operation)
                .amount(amount)
                .userId(userId)
                .record(rock.getRecord().add(amount))
                .build());
    }
}
