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("GetPlayerSets")]
public class GetPlayerSets : ICloudScriptFunction<FYGetPlayersSets, object?>
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserDataService _userDataService;

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

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

        var userId = context.User.FindAuthUserId();

        // Return the player's persisted loadout (written by CompleteInventoryUpdate /
        // RequestUpdateStationInventory) instead of a blank set, so saved gear survives
        // a menu reopen / relog. Same response shape as before, just populated.
        var userData = await _userDataService.FindAsync(userId, userId, new List<string> { "LOADOUT" });
        var loadout = JsonSerializer.Deserialize<LoadoutData>(userData["LOADOUT"].Value) ?? new LoadoutData();

        return new
        {
            success = true,
            entries = new[]
            {
                new
                {
                    setData = new
                    {
                        id = "",
                        userId,
                        kit = "",
                        shield = loadout.Shield ?? "",
                        helmet = loadout.Helmet ?? "",
                        weaponOne = loadout.WeaponOne ?? "",
                        weaponTwo = loadout.WeaponTwo ?? "",
                        bag = loadout.Bag ?? "",
                        bagItemsAsJsonStr = loadout.BagItemsAsJsonStr ?? "",
                        safeItemsAsJsonStr = loadout.SafeItemsAsJsonStr ?? ""
                    },
                    items = Array.Empty<object>()
                }
            }
        };
    }
}
