#pragma once

#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "IDCChatClient.generated.h"

DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnChatJsonResponse, bool, bSuccess, const FString&, JsonPayload);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnChatError, const FString&, ErrorMessage);

/**
 * REST client for GamePanel friends chat (/api/v1/chat).
 * Real-time Reverb: see docs/CHAT_API.md (Pusher protocol + auth_endpoint).
 */
UCLASS(BlueprintType, Blueprintable)
class IDCGAMES_API UIDCChatClient : public UObject
{
	GENERATED_BODY()

public:
	UPROPERTY(BlueprintReadWrite, Category = "IDC Chat")
	FString ApiBaseUrl = TEXT("http://localhost:8000");

	UPROPERTY(BlueprintReadWrite, Category = "IDC Chat")
	FString AccessToken;

	UPROPERTY(BlueprintAssignable, Category = "IDC Chat")
	FOnChatJsonResponse OnConversationOpened;

	UPROPERTY(BlueprintAssignable, Category = "IDC Chat")
	FOnChatJsonResponse OnMessagesLoaded;

	UPROPERTY(BlueprintAssignable, Category = "IDC Chat")
	FOnChatJsonResponse OnMessageSent;

	UPROPERTY(BlueprintAssignable, Category = "IDC Chat")
	FOnChatError OnChatError;

	UFUNCTION(BlueprintCallable, Category = "IDC Chat")
	void OpenConversation(int32 FriendUserId);

	UFUNCTION(BlueprintCallable, Category = "IDC Chat")
	void LoadMessages(int32 ConversationId, int32 PerPage = 50);

	UFUNCTION(BlueprintCallable, Category = "IDC Chat")
	void SendChatMessage(int32 ConversationId, const FString& Body, const FString& ClientMessageId);

	UFUNCTION(BlueprintCallable, Category = "IDC Chat")
	void MarkConversationRead(int32 ConversationId, int32 MessageId);

	UFUNCTION(BlueprintCallable, Category = "IDC Chat")
	void FetchRealtimeConfig();

private:
	void SendAuthorizedRequest(const FString& Verb, const FString& Path, const FString& JsonBody,
		TFunction<void(bool, const FString&)> Callback);

	static FString ExtractDataJson(const FString& ResponseBody, bool& bSuccess);
};
