package dev.rheinsw.gateway.security;

import dev.rheinsw.gateway.model.ApiKey;
import dev.rheinsw.gateway.model.ApiKeyType;
import dev.rheinsw.gateway.repository.ApiKeyRepository;
import dev.rheinsw.gateway.service.ApiKeyValidator;
import org.junit.jupiter.api.Test;

import java.util.Optional;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class ApiKeyValidatorTest {

    private final ApiKeyRepository repository = mock(ApiKeyRepository.class);
    private final ApiKeyValidator validator = new ApiKeyValidator(repository);

    @Test
    void testAuthorizedFrontendKey() {
        ApiKey key = ApiKey.builder()
                .apiKey("frontend-key")
                .type(ApiKeyType.FRONTEND)
                .enabled(true)
                .frontendOnly(true)
                .allowedServices(Set.of("contactService"))
                .build();

        when(repository.findByApiKey("frontend-key")).thenReturn(Optional.of(key));

        boolean result = validator.isAuthorized("frontend-key", "contactService", true);
        assertTrue(result);
    }

    @Test
    void testUnauthorizedDueToWrongService() {
        ApiKey key = ApiKey.builder()
                .apiKey("internal-key")
                .type(ApiKeyType.INTERNAL)
                .enabled(true)
                .frontendOnly(false)
                .allowedServices(Set.of("mailService"))
                .build();

        when(repository.findByApiKey("internal-key")).thenReturn(Optional.of(key));

        boolean result = validator.isAuthorized("internal-key", "contactService", false);
        assertFalse(result);
    }
}
