package com.codebyte.api.auth.repository;

import com.codebyte.api.auth.domain.OneTimeToken;
import com.codebyte.api.auth.domain.TokenType;
import com.codebyte.api.auth.domain.User;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
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;

/** Repository for {@link OneTimeToken}. */
public interface OneTimeTokenRepository extends JpaRepository<OneTimeToken, UUID> {

    Optional<OneTimeToken> findByTokenHashAndType(String tokenHash, TokenType type);

    /** Marks every still-active token of a kind as consumed (used by resend / reset in Phase 6). */
    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query(
            "update OneTimeToken t set t.consumedAt = :now "
                    + "where t.user = :user and t.type = :type and t.consumedAt is null")
    int consumeAllActive(
            @Param("user") User user, @Param("type") TokenType type, @Param("now") Instant now);
}
