using System.Text.Json;
using Prospect.Server.Api.Services.Auth.Extensions;
using Prospect.Server.Api.Services.CloudScript.Models;
using Prospect.Server.Api.Services.UserData;

namespace Prospect.Server.Api.Services.CloudScript.Functions;

[CloudScriptFunction("RequestFactionProgression")]
public class RequestFactionProgression : ICloudScriptFunction<FYQueryFactionProgressionRequest, object?>
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserDataService _userDataService;

    public RequestFactionProgression(IHttpContextAccessor httpContextAccessor, UserDataService userDataService)
    {
        _httpContextAccessor = httpContextAccessor;
        _userDataService = userDataService;
    }

    public async Task<object?> ExecuteAsync(FYQueryFactionProgressionRequest request)
    {
        var context = _httpContextAccessor.HttpContext;
        if (context == null)
        {
            return null;
        }
        var userId = context.User.FindAuthUserId();

        var userData = await _userDataService.FindAsync(
            userId, userId,
            new List<string> { "FactionProgressionICA", "FactionProgressionKorolev", "FactionProgressionOsiris" }
        );

        int Progression(string faction) =>
            userData.TryGetValue("FactionProgression" + faction, out var v) && v.Value != null
                ? JsonSerializer.Deserialize<int>(v.Value)
                : 0;

        return new
        {
            factions = new[]
            {
                new { factionId = "ICA", currentProgression = Progression("ICA") },
                new { factionId = "Korolev", currentProgression = Progression("Korolev") },
                new { factionId = "Osiris", currentProgression = Progression("Osiris") },
            },
            userId,
            error = ""
        };
    }
}
