/*
 * Caches user auth data (active status, token version) so the
 * JWT filter doesn't hit the database on every request.
 *
 * Author: Harkamal
 * Date: April 2026
 */
package com.petshop.backend.security;

import com.petshop.backend.repository.UserRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserAuthCacheService {

    private final UserRepository userRepository;

    public UserAuthCacheService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public record UserAuthData(Boolean active, Integer tokenVersion) {}

    @Cacheable(value = "userAuthCache", key = "#userId")
    public UserAuthData loadAuthData(Long userId) {
        return userRepository.findById(userId)
                .map(u -> new UserAuthData(u.getActive(), u.getTokenVersion()))
                .orElse(null);
    }

    @CacheEvict(value = "userAuthCache", key = "#userId")
    public void evict(Long userId) {
    }
}
