package ru.soune.nocopy.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import ru.soune.nocopy.entity.payout.PayoutMethod;
import ru.soune.nocopy.entity.user.User;

import java.util.List;
import java.util.Optional;

@Repository
public interface PayoutMethodRepository extends JpaRepository<PayoutMethod, String> {

    Optional<PayoutMethod> findByIdAndUserId(Long id, Long userId);

    @Query("SELECT p FROM PayoutMethod p WHERE p.user.Id = :userId AND TYPE(p) = :type")
    Optional<PayoutMethod> findByUserAndType(@Param("userId") Long userId,
                                             @Param("type") Class<? extends PayoutMethod> type);

    List<PayoutMethod> findByUserId(Long userId);

    Optional<PayoutMethod> findByUserIdAndIsDefaultTrue(Long userId);

    long countByUserId(Long userId);

    @Query("SELECT COUNT(c) > 0 FROM CardPayoutMethod c WHERE c.cardHash = :cardHash")
    boolean existsByCardHash(@Param("cardHash") String cardHash);

    @Modifying
    @Query("UPDATE PayoutMethod p SET p.isDefault = false WHERE p.user.id = :userId AND p.id != :methodId")
    void clearOtherDefault(@Param("userId") Long userId, @Param("methodId") Long methodId);

    Long user(User user);
}
