using Godot;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using SessionZeroClient.API;

namespace SessionZeroClient;

public class AccountManager(IApiHandler apiHandler)
{
    public string Username { get; private set; } = "";
    public string Email { get; private set; } = "";
    public string Jwt { get; private set; } = "";
    
    private IApiHandler _apiHandler = apiHandler;
    
    public async Task<bool> Register(string url, string username, string email, string password)
    {
        var response = await _apiHandler.Register(url, username, email, password);
    
        if (!string.IsNullOrEmpty(response))
        {
            var responseData = JsonSerializer.Deserialize<Dictionary<string, string>>(response);
            if (responseData != null && responseData.ContainsKey("message") && responseData["message"] == "User registered successfully")
            {
                return true;
            }
        }
    
        return false;
    }
    
    public async Task<bool> Login(string url, string username, string password)
    {
        var response = await _apiHandler.Login(url, username, password);
    
        if (!string.IsNullOrEmpty(response))
        {
            var responseData = JsonSerializer.Deserialize<Dictionary<string, string>>(response);
            if (responseData != null && responseData.ContainsKey("token"))
            {
                Jwt = responseData["token"];
                Username = username;
                return true;
            }
        }
    
        return false;
    }
    
    public void Logout()
    {
        Jwt = "";
        Username = "";
        Email = "";
    }
}
