extends Node

# ------------------------------------------------------------
# GameManager
# ------------------------------------------------------------
# Glabā spēles stāvokli starp scenām.

var selected_level: int = 1
var current_username: String = "guest"
var current_user_id: int = 0
@onready var net: Node = get_node_or_null("/root/NetAPI")

func _net() -> Node:
	# NetAPI ir autoload ar nosaukumu "NetAPI"
	return get_node_or_null("/root/NetAPI")

func get_level_name(lvl: int) -> String:
	return "Level %d" % lvl

func set_user(username: String, user_id: int = -1) -> void:
	current_username = username.strip_edges()
	current_user_id = user_id
	if current_username == "":
		current_username = "guest"

# -------- Auth wrappers (ērti UI pusē) --------

func login(username: String, password: String) -> Dictionary:
	var net := _net()
	if net == null:
		return {"ok": false, "error": "NetAPI autoload not found"}
	var res: Dictionary = await net.call("login", username, password)
	if res.get("ok", false):
		set_user(username, int(res.get("user_id", -1)))
	return res

func register(username: String, password: String) -> Dictionary:
	var net := _net()
	if net == null:
		return {"ok": false, "error": "NetAPI autoload not found"}
	var res: Dictionary = await net.call("register", username, password)
	if res.get("ok", false):
		# pēc reģistrācijas automātiski ielogojam
		set_user(username, int(res.get("user_id", -1)))
	return res

# -------- Score save --------

func save_result_to_db(result_text: String, score: int, time_sec: int) -> void:
	# Guest rezultātus nesaglabā
	if current_username == "" or current_username.to_lower() == "guest":
		print("[GameManager] Guest result not saved.")
		return

	# Zaudējumus nesaglabā leaderboard tabulā
	if result_text != "win":
		print("[GameManager] Lose result not saved.")
		return

	var net := _net()
	if net == null or not net.has_method("save_score"):
		print("[GameManager] NetAPI not found, score not saved.")
		return

	var payload_username: String = current_username.strip_edges()
	var uid: int = int(current_user_id)

	var res: Dictionary = await net.call(
		"save_score",
		payload_username,
		selected_level,
		score,
		time_sec,
		result_text,
		uid
	)

	if not res.get("ok", false):
		print("[GameManager] Failed to save score:", res)

func set_login(username: String, user_id: int) -> void:
	current_username = username
	current_user_id = user_id

func logout() -> void:
	current_username = "guest"
	current_user_id = 0
