package com.vaessl.app.search;

import static com.vaessl.app.Mockdata.MOCK_PASS;
import static com.vaessl.app.Mockdata.MOCK_USER;
import static com.vaessl.app.Mockdata.VALID_HOMEBOX_ALL_ITEMS_QUERY_RESPONSE;
import static com.vaessl.app.Mockdata.VALID_HOMEBOX_LOGIN_RESPONSE;

import static com.vaessl.app.shared.Endpoint.LOGIN;
import static com.vaessl.app.shared.Endpoint.SEARCH;
import static com.vaessl.app.shared.Endpoint.HOMEBOX_QUERY_ALL_ITEMS;
import static com.vaessl.app.shared.Endpoint.HOMEBOX_LOGIN;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import jakarta.servlet.http.Cookie;

/**
 * Integration tests for {@code POST /api/search}, verifying the session-gated
 * contract and request validation against a mocked Homebox backend (via WireMock)
 * and a real Spring MVC dispatch chain (via {@link MockMvc}).
 */
@SpringBootTest
@AutoConfigureMockMvc
@WireMockTest
class SearchControllerTest {

    @Autowired
    MockMvc mockMvc;

    private static final String QUERY_ALL_ITEMS = HOMEBOX_QUERY_ALL_ITEMS.getValue();

    private static final String LOGIN_PATH = LOGIN.getValue();

    private static final String SEARCH_REQUEST = SEARCH.getValue();

    /**
     * Logs in against a stubbed Homebox instance, then performs a keyword search using
     * the resulting session cookie. Expects {@code 200 OK} with the mocked item mapped
     * into the paged response body.
     *
     * @param wm WireMock runtime info, injected by {@link WireMockTest}, used to point
     *           the client at the stub server
     */
    @Test
    void shouldReturnListOfQueriedHomeboxItems(WireMockRuntimeInfo wm) throws Exception {

        WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue())
                .willReturn(WireMock.okJson(VALID_HOMEBOX_LOGIN_RESPONSE)));

        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(QUERY_ALL_ITEMS))
                .willReturn(WireMock.okJson(VALID_HOMEBOX_ALL_ITEMS_QUERY_RESPONSE)));

        MvcResult loginResult =
                mockMvc.perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON)
                        .content(connectionRequestBody(wm))).andExpect(status().isOk()).andReturn();

        Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION");

        mockMvc.perform(post(SEARCH_REQUEST).cookie(sessionCookie)
                .contentType(MediaType.APPLICATION_JSON).content(searchRequestBody(wm, "HOMEBOX")))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.content[0].title").value("MacBook Pro A1398"))
                .andExpect(jsonPath("$.totalElements").value(1))
                .andExpect(jsonPath("$.content[0].extraData.locationName")
                        .value("Server Schrank Ikea weiß"));
    }

    /**
     * Calls {@code /api/search} with no session cookie attached and expects
     * {@code 401 Unauthorized}, confirming the endpoint is session-gated.
     */
    @Test
    void shouldReturnUnauthorizedWhenNoSession() throws Exception {
        mockMvc.perform(post(SEARCH_REQUEST).contentType(MediaType.APPLICATION_JSON).content("""
                {
                    "appUrl": "http://irrelevant",
                    "query": "Item",
                    "serviceType": "HOMEBOX",
                    "username": "irrelevant",
                    "aiSearch": false
                }
                """)).andExpect(status().isUnauthorized());
    }

    /**
     * Sends a search request with a {@code serviceType} that doesn't map to any known
     * {@link com.vaessl.app.shared.ServiceType} and expects {@code 400 Bad Request}.
     */
    @Test
    void shouldReturnBadRequestWhenServiceTypeIsInvalid() throws Exception {
        mockMvc.perform(post(SEARCH_REQUEST).contentType(MediaType.APPLICATION_JSON)
                .content(searchRequestBody("INVALID_SERVICETYPE")))
                .andExpect(status().isBadRequest());
    }

    private String searchRequestBody(WireMockRuntimeInfo wm, String serviceType) {
        return searchRequestBody(wm.getHttpBaseUrl(), serviceType, false);
    }

    private String searchRequestBody(String serviceType) {
        return searchRequestBody("http://irrelevant", serviceType, false);
    }

    private String searchRequestBody(String appUrl, String serviceType, boolean aiSearch) {
        return """
                {
                    "appUrl": "%s",
                    "query": "Item",
                    "serviceType": "%s",
                    "username": "%s",
                    "aiSearch": "%b"
                }
                """.formatted(appUrl, serviceType, MOCK_USER, aiSearch);
    }

    private String connectionRequestBody(WireMockRuntimeInfo wm) {
        return """
                {
                    "appUrl": "%s",
                    "serviceType": "HOMEBOX",
                    "username": "%s",
                    "password": "%s"
                }
                """.formatted(wm.getHttpBaseUrl(), MOCK_USER, MOCK_PASS);
    }
}
