package com.bizzan.bitrade.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bizzan.bitrade.dao.SpotWalletSnapshotDao;
import com.bizzan.bitrade.entity.ExchangeWallet;
import com.bizzan.bitrade.entity.SpotWalletSnapshot;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SpotWalletSnapshotService {

    @Autowired
    private SpotWalletSnapshotDao dao;

    /**
     * 查询指定会员昨日现货账户快照总价值（USDT）
     * 若无快照数据（首次运行）则返回 ZERO
     */
    public BigDecimal getYesterdayValue(Long memberId) {
        BigDecimal value = dao.sumYesterdayValueByMemberId(memberId);
        return value != null ? value : BigDecimal.ZERO;
    }

    /**
     * 保存一个会员的现货持仓快照
     *
     * @param memberId 会员ID
     * @param wallets  该会员所有现货钱包
     * @param priceMap 快照时的价格表，key = "BTC/USDT" 格式，value = 价格
     */
    @Transactional
    public void saveSnapshot(Long memberId, List<ExchangeWallet> wallets, Map<String, BigDecimal> priceMap) {
        for (ExchangeWallet wallet : wallets) {
            BigDecimal quantity = wallet.getBalance().add(wallet.getFrozenBalance());
            if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }

            BigDecimal price;
            if ("USDT".equalsIgnoreCase(wallet.getCoinId())) {
                price = BigDecimal.ONE;
            } else {
                String key = wallet.getCoinId() + "/USDT";
                price = priceMap.get(key);
                if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
                    continue; // 无价格数据的币种跳过
                }
            }

            SpotWalletSnapshot snapshot = new SpotWalletSnapshot();
            snapshot.setMemberId(memberId);
            snapshot.setCoinUnit(wallet.getCoinId());
            snapshot.setQuantity(quantity);
            snapshot.setPrice(price);
            dao.save(snapshot);
        }
    }

    /**
     * 清理 N 天前的旧快照
     */
    @Transactional
    public void cleanOldSnapshots(int keepDays) {
        dao.deleteSnapshotsOlderThan(keepDays);
    }
}
