package org.raddatz.familienarchiv;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalManagementPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import software.amazon.awssdk.services.s3.S3Client;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@Import(PostgresContainerConfig.class)
class ActuatorSecurityTest {

    @LocalManagementPort
    private int managementPort;

    @MockitoBean
    S3Client s3Client;

    @Test
    void actuator_health_is_accessible_without_authentication() {
        ResponseEntity<String> response = noThrowTemplate().getForEntity(
                "http://localhost:" + managementPort + "/actuator/health", String.class);

        assertThat(response.getStatusCode().value()).isEqualTo(200);
    }

    @Test
    void actuator_env_requires_authentication() {
        ResponseEntity<String> response = noThrowTemplate().getForEntity(
                "http://localhost:" + managementPort + "/actuator/env", String.class);

        assertThat(response.getStatusCode().value()).isEqualTo(401);
    }

    private RestTemplate noThrowTemplate() {
        RestTemplate template = new RestTemplate();
        template.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public boolean hasError(org.springframework.http.client.ClientHttpResponse response) throws IOException {
                return false;
            }
        });
        return template;
    }
}
