package dev.rheinsw.gateway.service;

import dev.rheinsw.gateway.model.ApiKey;
import dev.rheinsw.gateway.repository.ApiKeyRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Thatsaphorn Atchariyaphap
 * @since 25.04.25
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ApiKeyValidator {

    private final ApiKeyRepository apiKeyRepository;

    public boolean isAuthorized(String key, String targetService, boolean isFrontendRequest) {
        return apiKeyRepository.findByApiKey(key)
                .filter(ApiKey::isEnabled)
                .filter(apiKey -> !apiKey.isFrontendOnly() || isFrontendRequest)
                .filter(apiKey -> apiKey.getAllowedServices().contains(targetService))
                .isPresent();
    }
}
