using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Pgo.Backend.Models;

public class LoginState
{
    [JsonPropertyName("p")]
    public string ProviderName { get; set; } = "";

    [JsonPropertyName("s")]
    public string SessionId { get; set; } = "";

    public static string Create(string providerName)
    {
        var state = JsonSerializer.Serialize<LoginState>(new()
        {
            ProviderName = providerName,
            SessionId = Guid.NewGuid().ToString("N") // Generate a random state.
        });

        return Convert.ToBase64String(Encoding.UTF8.GetBytes(state));
    }

    public static LoginState Parse(string? state)
    {
        if (state == null)
        {
            return new();
        }
        var json = Encoding.UTF8.GetString(Convert.FromBase64String(state));
        return JsonSerializer.Deserialize<LoginState>(json) ?? new();
    }
}
