class_name HTTPTalkpalClient
extends Node

signal request_failed(error_message: String)

var _base_url: String
var _jwt_token: String = ""
var _timed_out := false

func _init(_base_url: String):
	self._base_url = _base_url

func set__jwt_token(token: String):
	_jwt_token = token

func request(endpoint: String, method: int, body: String = "") -> Variant:
	var request = HTTPRequest.new()
	add_child(request)

	var url = _base_url + endpoint
	var headers = PackedStringArray([
		"Content-Type: application/json",
		"Authorization: Bearer %s" % _jwt_token
	])

	var error = request.request(url, headers, method, body)
	if error != OK:
		request.queue_free()
		emit_signal("request_failed", "Request creation failed: %d" % error)
		print("request_failed", "Request creation failed: %d" % error)
		return null

	var response = await _wait_for_request_or_timeout(request)
	request.queue_free()

	var result = response[0]
	var response_code = response[1]
	var response_body = response[3]

	if result != HTTPRequest.RESULT_SUCCESS:
		emit_signal("request_failed", "HTTP request failed: %d" % result)
		return null

	var json = JSON.new()
	var parse_error = json.parse(response_body.get_string_from_utf8())

	if parse_error != OK:
		emit_signal("request_failed", "JSON parse error: %d" % parse_error)
		return null

	var response_data = json.get_data()

	if response_code >= 400:
		emit_signal("request_failed", response_data.get("error", "Unknown error"))
		return null

	return response_data

func _wait_for_request_or_timeout(request: HTTPRequest) -> Array:
	var timer = Timer.new()
	add_child(timer)
	timer.wait_time = 5.0
	timer.one_shot = true
	timer.timeout.connect(func():
		_timed_out = true
		if request.get_http_client_status() != HTTPClient.STATUS_DISCONNECTED:
			request.cancel_request()
	)
	timer.start()

	while true:
		if _timed_out:
			_timed_out = false
			timer.queue_free()
			return [HTTPRequest.RESULT_REQUEST_FAILED, 408, [], PackedByteArray()]
		if request.get_http_client_status() == HTTPClient.STATUS_REQUESTING:
			break
		await get_tree().process_frame

	timer.queue_free()
	return await request.request_completed
