using System.Text.Json;
using System.Text.Json.Serialization;
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;

// Persisted presence, read back by GetFriendList to show friends' online / in-match state.
public class PlayerPresenceState
{
    [JsonPropertyName("inMatch")]
    public bool InMatch { get; set; }
    [JsonPropertyName("lastSeenUtc")]
    public long LastSeenUtc { get; set; }
}

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

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

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

        var userId = context.User.FindAuthUserId();
        var state = new PlayerPresenceState
        {
            InMatch = request.InMatch,
            LastSeenUtc = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
        };
        await _userDataService.UpdateAsync(
            userId, userId,
            new Dictionary<string, string> { ["PresenceState"] = JsonSerializer.Serialize(state) }
        );

        return new { };
    }
}
