package com.izouma.nineth.repo;

import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.enums.AssetStatus;
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.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

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

    long countByIpfsUrlAndStatusNot(String ipfsUrl, AssetStatus status);

    List<Asset> findByCollectionId(Long collectionId);

    List<Asset> findByCollectionIdAndStatusIn(Long collectionId, Iterable<AssetStatus> statuses);

    List<Asset> findByCreatedAtBefore(LocalDateTime localDateTime);

    List<Asset> findByConsignmentTrue();

    List<Asset> findByTokenIdIn(Iterable<String> tokenId);

    List<Asset> findByTokenIdOrderByCreatedAt(String tokenId);

    List<Asset> findByOrderId(Long orderId);

    @Query("select a from Asset a join Order o on o.assetId = a.id join Asset aa on aa.orderId = o.id where a.id = ?1")
    Optional<Asset> findChild(Long id);

    @Query("select a from Asset a join User u on a.userId = u.id where a.consignment = true and u.settleAccountId is null")
    List<Asset> findNoAccount();

    List<Asset> findByTxHash(String hash);

    List<Asset> findByIdIn(Iterable<Long> ids);

    @Query("select a from Asset a left join TokenHistory t on a.tokenId = t.tokenId where t.id is null")
    List<Asset> findByNoHistory();


    List<Asset> findByTokenIdAndCreatedAtBetween(String tokenId, LocalDateTime start, LocalDateTime end);

    Asset findFirstByTokenId(String tokenId);

    Asset findFirstByTxHashIsNullAndTokenIdNotNullAndStatusOrderByCreatedAt(AssetStatus status);

    List<Asset> findByTxHashIsNullAndTokenIdNotNullAndCreatedAtBefore(LocalDateTime time);

    List<Asset> findAllByIdInAndUserId(Collection<Long> id, Long userId);
}