package org.initialde.yakasave.Integration;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.initialde.yakasave.Api.Requests.LoginRequest;
import org.initialde.yakasave.Api.Responses.UserProfileResponse;
import org.initialde.yakasave.Infrastructure.Persistence.UserRepository;
import org.initialde.yakasave.Infrastructure.authentication.AuthenticationGateway;
import org.initialde.yakasave.UserFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class RetrieveMeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthenticationGateway authenticationGateway;

    @Autowired
    private UserRepository userRepository;

    @Test
    public void shouldRetrieveMyProfileTest() throws Exception {
        final var userCredentials = new LoginRequest("John Doe", "toto1234");
        final var user = UserFactory.create("John Doe", "toto1234");
        userRepository.save(user);

        String token = authenticationGateway.authenticate(userCredentials);

        MvcResult result = this.mockMvc.perform(get("/users/me")
                        .header("Authorization", "Bearer " + token)
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();

        String json = result.getResponse().getContentAsString();
        UserProfileResponse userResponse = objectMapper.readValue(json, new TypeReference<>() {});

        assertEquals(user.getUsername(), userResponse.username());
    }
}
