package cn.nianxx.thhotel.workflows.reservation.control;

import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import cn.nianxx.thhotel.ThHotelApplication;
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.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest(
        classes = ThHotelApplication.class,
        properties = {
                "superagent.task-result.hmac-secret=test-superagent-secret",
                "superagent.task-result.max-body-bytes=16"
        })
@AutoConfigureMockMvc
@ActiveProfiles("test")
class SuperAgentTaskResultMaxBodyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void shouldRejectBodyLargerThanConfiguredLimitBeforeParsingJson() throws Exception {
        mockMvc.perform(post("/api/integrations/superagent/task-results")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"source_message_id\":\"too-large\"}"))
                .andExpect(status().isPayloadTooLarge())
                .andExpect(jsonPath("$.error_code").value("REQUEST_BODY_TOO_LARGE"))
                .andExpect(content().string(not(containsString("test-superagent-secret"))));
    }

    @Test
    void shouldRejectBodyLargerThanConfiguredLimitWhenContextPathIsConfigured() throws Exception {
        mockMvc.perform(post("/hotel/api/integrations/superagent/task-results")
                        .contextPath("/hotel")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"source_message_id\":\"too-large-context-path\"}"))
                .andExpect(status().isPayloadTooLarge())
                .andExpect(jsonPath("$.error_code").value("REQUEST_BODY_TOO_LARGE"));
    }
}
