extends Node

# ------------------------------------------------------------
# NetAPI (autoload singleton)
# ------------------------------------------------------------

@export var base_url: String = "http://127.0.0.1/fighter_api"

var last_error: String = ""

@onready var _http: HTTPRequest = HTTPRequest.new()

func _ready() -> void:
	add_child(_http)

# ------------------------ public API ------------------------

func ping() -> Dictionary:
	return await _request_json("/ping.php", HTTPClient.METHOD_GET)

func register_user(username: String, password: String) -> Dictionary:
	var body: Dictionary = {"username": username, "password": password}
	return await _request_json("/register.php", HTTPClient.METHOD_POST, body)

func login_user(username: String, password: String) -> Dictionary:
	var body: Dictionary = {"username": username, "password": password}
	return await _request_json("/login.php", HTTPClient.METHOD_POST, body)

func save_score(username: String, level: int, score: int, match_time_sec: int, result: String, user_id: int = 0) -> Dictionary:
	# result: "win" vai "lose"
	var body: Dictionary = {
		"username": username,
		"user_id": user_id,
		"level": level,
		"score": score,
		"match_time_sec": match_time_sec,
		"result": result
	}
	return await _request_json("/save_score.php", HTTPClient.METHOD_POST, body)

func get_scores(limit: int = 20, level: int = 0) -> Dictionary:
	# ja level=0 -> visi
	var query := "?limit=%d" % limit
	if level > 0:
		query += "&level=%d" % level
	return await _request_json("/get_scores.php" + query, HTTPClient.METHOD_GET)

# ------------------------ internals ------------------------

func _request_json(path: String, method: int, body_dict: Dictionary = {}) -> Dictionary:
	last_error = ""

	var url := base_url.rstrip("/") + path
	var headers: PackedStringArray = [
		"Accept: application/json",
		"Content-Type: application/json"
	]

	var body_str := ""
	if method == HTTPClient.METHOD_POST or method == HTTPClient.METHOD_PUT:
		body_str = JSON.stringify(body_dict)

	var err := _http.request(url, headers, method, body_str)
	if err != OK:
		last_error = "HTTPRequest.request() failed: %s" % err
		return {"ok": false, "error": last_error}

	var result: Array = await _http.request_completed
	var response_code: int = int(result[1])
	var raw: PackedByteArray = result[3]
	var text: String = raw.get_string_from_utf8()

	if response_code < 200 or response_code >= 300:
		last_error = "HTTP %d: %s" % [response_code, text]
		return {"ok": false, "error": last_error}

	var parsed: Variant = JSON.parse_string(text)
	if parsed == null:
		return {"ok": false, "error": "Invalid JSON from server", "raw": text}

	if parsed is Dictionary:
		var d: Dictionary = parsed
		if not d.has("ok"):
			d["ok"] = true
		return d

	return {"ok": true, "data": parsed}
