package cn.nianxx.thhotel.support;

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

import com.jayway.jsonpath.JsonPath;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

/**
 * MockMvc 登录辅助工具。测试仍走真实登录接口，避免绕过后端安全链路。
 */
public final class MockMvcAuthTestSupport {

    private MockMvcAuthTestSupport() {
    }

    /**
     * 通过真实登录接口获取 Bearer token。
     */
    public static String loginToken(MockMvc mockMvc, String username, String password) throws Exception {
        MvcResult result = mockMvc.perform(post("/api/auth/login")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {
                                  "username": "%s",
                                  "password": "%s",
                                  "preferred_hotel_id": "HOTEL-TEST"
                                }
                        """.formatted(username, password)))
                .andExpect(status().isOk())
                .andReturn();
        return JsonPath.read(result.getResponse().getContentAsString(), "$.access_token");
    }

    /**
     * 使用指定 token 执行已授权请求。
     */
    public static ResultActions performAuthorized(
            MockMvc mockMvc,
            String token,
            MockHttpServletRequestBuilder requestBuilder) throws Exception {
        return mockMvc.perform(requestBuilder.header("Authorization", "Bearer " + token));
    }
}
