package com.eactive.eai.kjb.errors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

class OAuth2TokenSuccessTest {

	private final ObjectMapper objectMapper = new ObjectMapper();

	@Test
	void testCase001_토큰발급성공() throws Exception {
		// given
		String url = TestConfig.getBaseUrl("/oauth2/token");

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("grant_type", "client_credentials"));
		params.add(new BasicNameValuePair("client_id", "AyeWx0OpYLJbHpZ21DDSxYfQPmD5Ckn8"));
		params.add(new BasicNameValuePair("client_secret", "KwBYJT1m1v3SUvzN2HPHhy2Ad9Q2GADbgWkYZZg9Ybbc8R1uEuBJNQ9oVl13b1qiXwYvDWTaX0EanxY4SMjNfnBBsZzfNoMwwDPTb3IjQy5k3CRxTAYzcSnmzlC4FSsG"));
		params.add(new BasicNameValuePair("scope", "api"));

		// when
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));

			String responseBody = httpClient.execute(httpPost, response -> {
				String body = EntityUtils.toString(response.getEntity());
				System.out.println("Response Body: " + body);

				// then
				assertEquals(200, response.getCode());
				return body;
			});

			// 응답 검증
			JsonNode jsonNode = objectMapper.readTree(responseBody);
			assertNotNull(jsonNode, "JSON 응답이 null입니다");

			// OAuth2 토큰 응답 필드 확인
			assertNotNull(jsonNode.get("access_token"), "access_token 필드가 없습니다");
			assertNotNull(jsonNode.get("token_type"), "token_type 필드가 없습니다");
			assertNotNull(jsonNode.get("expires_in"), "expires_in 필드가 없습니다");

			String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
			System.out.println("Token Response:");
			System.out.println(prettyJson);
		}
	}
}
