package com.malk.service.eiam.impl;

import com.malk.server.common.McException;
import com.malk.server.eiam.EiamApiResponse;
import com.malk.server.eiam.EiamConf;
import com.sun.net.httpserver.HttpServer;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

import java.net.InetSocketAddress;
import java.util.Collections;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

/**
 * EIAM 用户写接口响应解析测试。
 */
public class EiamClient_UserImplTest {

    @Test
    public void parseResponse_validJson_returnsPayload() {
        EiamApiResponse response = EiamClient_UserImpl.parseResponse(
                "{\"userId\":\"user_test\"}");

        assertEquals("user_test", response.getUserId());
    }

    @Test
    public void parseResponse_plainText_throwsBusinessException() {
        try {
            EiamClient_UserImpl.parseResponse("error");
            fail("应拒绝非 JSON 响应");
        } catch (McException ex) {
            assertEquals("EIAM_INVALID_RESPONSE", ex.getCode());
        }
    }

    @Test
    public void parseResponse_blank_throwsEmptyResponse() {
        try {
            EiamClient_UserImpl.parseResponse(" ");
            fail("应拒绝空响应");
        } catch (McException ex) {
            assertEquals("EIAM_EMPTY_RESPONSE", ex.getCode());
        }
    }

    @Test
    public void parseActionResponse_blank_returnsSuccessPayload() {
        EiamApiResponse response = EiamClient_UserImpl.parseActionResponse(" ");

        assertNull(response.getCode());
    }

    @Test
    public void patchUser_emptyResponse_returnsSuccessPayload() throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
        server.createContext("/v2/instance/application/users/user_test", exchange -> {
            exchange.sendResponseHeaders(204, -1);
            exchange.close();
        });
        server.start();
        try {
            EiamConf conf = new EiamConf();
            conf.setBaseUrl("http://127.0.0.1:" + server.getAddress().getPort());
            EiamClient_UserImpl client = new EiamClient_UserImpl();
            ReflectionTestUtils.setField(client, "eiamConf", conf);

            EiamApiResponse response = client.patchUser("token", "instance", "application",
                    "user_test", Collections.singletonMap("username", "17612168216"));

            assertNull(response.getCode());
        } finally {
            server.stop(0);
        }
    }
}
