extends Node

const CHARACTER_API_URL := "https://pchar.ranaze.com/api/Characters"

func list_characters() -> Dictionary:
	return await _request(HTTPClient.METHOD_GET, CHARACTER_API_URL)

func create_character(character_name: String) -> Dictionary:
	var payload := JSON.stringify({
		"name": character_name
	})
	return await _request(HTTPClient.METHOD_POST, CHARACTER_API_URL, payload)

func delete_character(character_id: String) -> Dictionary:
	var url := "%s/%s" % [CHARACTER_API_URL, character_id]
	return await _request(HTTPClient.METHOD_DELETE, url)

func update_character_coord(character_id: String, coord: Vector2i) -> Dictionary:
	var url := "%s/%s/coord" % [CHARACTER_API_URL, character_id]
	var payload := JSON.stringify({
		"coord": {
			"x": coord.x,
			"y": coord.y
		}
	})
	return await _request(HTTPClient.METHOD_PUT, url, payload)

func heartbeat_character(character_id: String) -> Dictionary:
	var url := "%s/%s/heartbeat" % [CHARACTER_API_URL, character_id]
	return await _request(HTTPClient.METHOD_POST, url, "")

func _request(method: int, url: String, body: String = "") -> Dictionary:
	var request := HTTPRequest.new()
	add_child(request)

	var headers := PackedStringArray()
	if not AuthState.access_token.is_empty():
		headers.append("Authorization: Bearer %s" % AuthState.access_token)
	if method == HTTPClient.METHOD_POST or method == HTTPClient.METHOD_PUT:
		headers.append("Content-Type: application/json")

	var err := request.request(url, headers, method, body)
	if err != OK:
		request.queue_free()
		return {
			"ok": false,
			"status": 0,
			"error": "Failed to send request (%s)." % err,
			"body": ""
		}

	var result: Array = await request.request_completed
	request.queue_free()

	var result_code: int = result[0]
	var response_code: int = result[1]
	var response_body: String = result[3].get_string_from_utf8()

	if result_code != HTTPRequest.RESULT_SUCCESS:
		return {
			"ok": false,
			"status": response_code,
			"error": "Network error (%s)." % result_code,
			"body": response_body
		}

	return {
		"ok": response_code >= 200 and response_code < 300,
		"status": response_code,
		"error": "",
		"body": response_body
	}
