extends Control

const AUTH_LOGIN_URL := "https://pauth.ranaze.com/api/Auth/login"

@onready var _username_input: LineEdit = %UsernameInput
@onready var _password_input: LineEdit = %PasswordInput
@onready var _login_request: HTTPRequest = %LoginRequest
@onready var _error_label: Label = %ErrorLabel

func _ready() -> void:
	if not _username_input.is_connected("text_submitted", Callable(self, "_on_input_text_submitted")):
		_username_input.text_submitted.connect(_on_input_text_submitted)
	if not _password_input.is_connected("text_submitted", Callable(self, "_on_input_text_submitted")):
		_password_input.text_submitted.connect(_on_input_text_submitted)

func _on_log_in_button_pressed() -> void:
	var username := _username_input.text.strip_edges()
	var password := _password_input.text
	if username.is_empty() or password.is_empty():
		_show_error("Username and password required.")
		return

	var payload := {
		"username": username,
		"password": password,
	}
	var headers := PackedStringArray(["Content-Type: application/json"])
	var err := _login_request.request(AUTH_LOGIN_URL, headers, HTTPClient.METHOD_POST, JSON.stringify(payload))
	if err != OK:
		_show_error("Failed to send login request.")

func _on_login_request_completed(result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray) -> void:
	var body_text := body.get_string_from_utf8()
	if result != HTTPRequest.RESULT_SUCCESS:
		_show_error("Network error. Please try again.")
		return

	if response_code >= 200 and response_code < 300:
		var response: Variant = JSON.parse_string(body_text)
		if typeof(response) == TYPE_DICTIONARY:
			#print("Login success for %s" % response.get("username", "unknown"))
			#print("Access Token: %s" % response.get("accessToken", ""))
			var token := String(response.get("accessToken", ""))
			var username := String(response.get("username", ""))
			AuthState.set_session(username, token)
			get_tree().change_scene_to_file("res://scenes/UI/character_screen.tscn")
	else:
		_show_error("Login failed. Check your credentials.")

func _on_back_button_pressed() -> void:
	get_tree().change_scene_to_file("res://scenes/UI/start_screen.tscn")

func _show_error(message: String) -> void:
	_error_label.text = message

func _on_input_text_submitted(_new_text: String) -> void:
	_on_log_in_button_pressed()
