package com.bizzan.bitrade.dao;

import java.math.BigDecimal;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.bizzan.bitrade.dao.base.BaseDao;
import com.bizzan.bitrade.entity.SpotWalletSnapshot;

public interface SpotWalletSnapshotDao extends BaseDao<SpotWalletSnapshot> {

    /**
     * 查询指定会员昨日快照的资产总价值（各币种 quantity * price 之和）
     */
    @Query(value = "SELECT COALESCE(SUM(s.quantity * s.price), 0) " +
                   "FROM spot_wallet_snapshot s " +
                   "WHERE s.member_id = :memberId " +
                   "  AND DATE(s.snapshot_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)",
           nativeQuery = true)
    BigDecimal sumYesterdayValueByMemberId(@Param("memberId") Long memberId);

    /**
     * 删除 N 天前的旧快照，避免数据膨胀
     */
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM spot_wallet_snapshot WHERE snapshot_date < DATE_SUB(NOW(), INTERVAL :days DAY)",
           nativeQuery = true)
    void deleteSnapshotsOlderThan(@Param("days") int days);
}
