package com.rj.controller;

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.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class QweiUserControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void syncCustomerShouldFetchFromQiWeiAndPrintToConsole() throws Exception {
        String tenantId = System.getProperty("tenantId", "TENANT_ID_CST_2026");
        var requestBuilder = post("/api/qweiUser/syncCustomer")
                .param("tenantId", tenantId);

        MvcResult mvcResult = mockMvc.perform(requestBuilder).andReturn();

        int statusCode = mvcResult.getResponse().getStatus();
        String responseBody = mvcResult.getResponse().getContentAsString();
        System.out.println("qwei customer sync status: " + statusCode);
        System.out.println("qwei customer sync response: " + responseBody);

        assertTrue(responseBody.contains("\"success\""), "响应缺少success字段: " + responseBody);
        if (statusCode == HttpStatus.OK.value()) {
            assertTrue(responseBody.contains("\"success\":true"), "同步失败: " + responseBody);
            return;
        }

        assertTrue(statusCode == HttpStatus.BAD_REQUEST.value(), "非预期状态码: " + statusCode + ", body=" + responseBody);
        assertTrue(responseBody.contains("48002") || responseBody.contains("api forbidden"),
                "当前失败不是企微权限问题，请排查: " + responseBody);
    }
}
