package org.brapi.test.BrAPITestServer.system.repository;

import org.brapi.test.BrAPITestServer.system.entity.SysUserEntity;
import org.brapi.test.BrAPITestServer.system.entity.UserSessionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;
import java.util.Optional;
import java.util.UUID;

public interface UserSessionRepository extends JpaRepository<UserSessionEntity, UUID> {

    @Query("""
            SELECT u FROM SysUserEntity u
            JOIN UserSessionEntity s ON s.userId = u.id
            WHERE u.id = :userId
              AND s.jti = :jti
              AND s.tokenHash = :tokenHash
              AND s.revokedAt IS NULL
              AND s.expiresAt > :now
            """)
    Optional<SysUserEntity> findActiveUserBySession(
            @Param("userId") UUID userId,
            @Param("jti") String jti,
            @Param("tokenHash") String tokenHash,
            @Param("now") Instant now);
}
