package com.izouma.nineth.repo;

import com.izouma.nineth.domain.AuctionRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;

public interface AuctionRecordRepo extends JpaRepository<AuctionRecord, Long>, JpaSpecificationExecutor<AuctionRecord> {
    @Query("update AuctionRecord t set t.del = true where t.id = ?1")
    @Modifying
    @Transactional
    void softDelete(Long id);

    AuctionRecord findTopByAuctionIdAndUserIdOrderByIdDesc(Long auctionId, Long userId);

    @Modifying
    @Transactional
    void deleteAllByAuctionId(Long auctionId);

    @Query(nativeQuery = true, value = "WITH ranked_messages AS (" +
            " SELECT m.*, ROW_NUMBER() OVER (PARTITION BY auction_id ORDER BY id DESC) AS rn" +
            "    FROM auction_record AS m where user_id = ?1 and auction_type = ?2)" +
            " SELECT * FROM ranked_messages WHERE rn = 1;")
    List<AuctionRecord> findByUserId(Long userId, String auctionType);

    @Query(nativeQuery = true, value = "WITH ranked_messages AS (" +
            " SELECT m.user_id, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY id DESC) AS rn" +
            "    FROM auction_record AS m where auction_id = ?1 and type = 'DEPOSIT' and pay_deposit = true)" +
            " SELECT * FROM ranked_messages WHERE rn = 1 limit ?2;")
    List<Long> findByAuctionId(Long auctionId, int size);
}
