#include "IDCVoiceMatchClient.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "Dom/JsonObject.h"
#include "Serialization/JsonSerializer.h"
#include "Serialization/JsonWriter.h"

void UIDCVoiceMatchClient::FetchVoiceConfig()
{
	SendAuthorizedRequest(TEXT("GET"), TEXT("/api/v1/voice/config"), TEXT(""),
		[this](bool bOk, const FString& Json)
		{
			OnVoiceConfigLoaded.Broadcast(bOk, Json);
		});
}

void UIDCVoiceMatchClient::CreateMatch(const FString& MatchKey, const TArray<int32>& MemberUserIds, const FString& Label)
{
	TSharedPtr<FJsonObject> Body = MakeShared<FJsonObject>();
	Body->SetStringField(TEXT("match_key"), MatchKey);
	TArray<TSharedPtr<FJsonValue>> Members;
	for (int32 Id : MemberUserIds)
	{
		Members.Add(MakeShared<FJsonValueNumber>(Id));
	}
	Body->SetArrayField(TEXT("member_user_ids"), Members);
	if (!Label.IsEmpty())
	{
		Body->SetStringField(TEXT("label"), Label);
	}
	FString Payload;
	TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Payload);
	FJsonSerializer::Serialize(Body.ToSharedRef(), Writer);

	SendAuthorizedRequest(TEXT("POST"), TEXT("/api/v1/matches"), Payload,
		[this](bool bOk, const FString& Json)
		{
			OnMatchCreated.Broadcast(bOk, Json);
		});
}

void UIDCVoiceMatchClient::JoinMatch(const FString& MatchKey, bool bVoiceEnabled)
{
	TSharedPtr<FJsonObject> Body = MakeShared<FJsonObject>();
	Body->SetBoolField(TEXT("voice_enabled"), bVoiceEnabled);
	if (bVoiceEnabled)
	{
		Body->SetStringField(TEXT("voice_provider"), VoiceProvider);
	}
	FString Payload;
	TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Payload);
	FJsonSerializer::Serialize(Body.ToSharedRef(), Writer);

	const FString Path = FString::Printf(TEXT("/api/v1/matches/%s/join"), *MatchKey);
	SendAuthorizedRequest(TEXT("POST"), Path, Payload,
		[this](bool bOk, const FString& Json)
		{
			OnMatchJoined.Broadcast(bOk, Json);
		});
}

void UIDCVoiceMatchClient::LeaveMatch(const FString& MatchKey)
{
	const FString Path = FString::Printf(TEXT("/api/v1/matches/%s/leave"), *MatchKey);
	SendAuthorizedRequest(TEXT("POST"), Path, TEXT("{}"),
		[this](bool bOk, const FString& Json)
		{
			if (!bOk)
			{
				OnVoiceMatchError.Broadcast(Json);
			}
		});
}

void UIDCVoiceMatchClient::SendMatchChatMessage(int32 ConversationId, const FString& Body, const FString& ClientMessageId)
{
	TSharedPtr<FJsonObject> JsonBody = MakeShared<FJsonObject>();
	JsonBody->SetStringField(TEXT("body"), Body);
	if (!ClientMessageId.IsEmpty())
	{
		JsonBody->SetStringField(TEXT("client_message_id"), ClientMessageId);
	}
	FString Payload;
	TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Payload);
	FJsonSerializer::Serialize(JsonBody.ToSharedRef(), Writer);

	const FString Path = FString::Printf(TEXT("/api/v1/chat/conversations/%d/messages"), ConversationId);
	SendAuthorizedRequest(TEXT("POST"), Path, Payload,
		[this](bool bOk, const FString& Json)
		{
			if (!bOk)
			{
				OnVoiceMatchError.Broadcast(Json);
			}
		});
}

void UIDCVoiceMatchClient::SendAuthorizedRequest(const FString& Verb, const FString& Path, const FString& JsonBody,
	TFunction<void(bool, const FString&)> Callback)
{
	if (AccessToken.IsEmpty())
	{
		OnVoiceMatchError.Broadcast(TEXT("Access token is required"));
		Callback(false, TEXT(""));
		return;
	}

	const FString Url = ApiBaseUrl.TrimEnd() + Path;
	TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
	Request->SetURL(Url);
	Request->SetVerb(Verb);
	Request->SetHeader(TEXT("Authorization"), FString::Printf(TEXT("Bearer %s"), *AccessToken));
	Request->SetHeader(TEXT("Accept"), TEXT("application/json"));
	if (!JsonBody.IsEmpty())
	{
		Request->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
		Request->SetContentAsString(JsonBody);
	}

	Request->OnProcessRequestComplete().BindLambda(
		[this, Callback](FHttpRequestPtr Req, FHttpResponsePtr Res, bool bConnected)
		{
			if (!bConnected || !Res.IsValid())
			{
				OnVoiceMatchError.Broadcast(TEXT("HTTP connection failed"));
				Callback(false, TEXT(""));
				return;
			}

			const FString Body = Res->GetContentAsString();
			if (Res->GetResponseCode() < 200 || Res->GetResponseCode() >= 300)
			{
				OnVoiceMatchError.Broadcast(Body);
				Callback(false, Body);
				return;
			}

			bool bSuccess = false;
			const FString DataJson = ExtractDataJson(Body, bSuccess);
			Callback(bSuccess, DataJson);
		});

	Request->ProcessRequest();
}

FString UIDCVoiceMatchClient::ExtractDataJson(const FString& ResponseBody, bool& bSuccess)
{
	bSuccess = false;
	TSharedPtr<FJsonObject> Root;
	TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseBody);
	if (!FJsonSerializer::Deserialize(Reader, Root) || !Root.IsValid())
	{
		return ResponseBody;
	}

	bool SuccessField = false;
	if (Root->TryGetBoolField(TEXT("success"), SuccessField) && SuccessField)
	{
		bSuccess = true;
		const TSharedPtr<FJsonObject>* DataObject;
		if (Root->TryGetObjectField(TEXT("data"), DataObject))
		{
			FString Out;
			TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Out);
			FJsonSerializer::Serialize((*DataObject).ToSharedRef(), Writer);
			return Out;
		}
	}

	return ResponseBody;
}
