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

public class ClientsideFriendsImportRequest
{
    [JsonPropertyName("platform")]
    public string Platform { get; set; }
    [JsonPropertyName("userIds")]
    public string[] UserIDs { get; set; }
}

public class ClientsideFriendsImportResponse
{
    // TODO: Unknown structure
}

[CloudScriptFunction("ClientsideFriendsImport")]
public class ClientsideFriendsImportFunction : ICloudScriptFunction<ClientsideFriendsImportRequest, ClientsideFriendsImportResponse>
{
    private readonly ILogger<ClientsideFriendsImportFunction> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserDataService _userDataService;

    public ClientsideFriendsImportFunction(ILogger<ClientsideFriendsImportFunction> logger, IHttpContextAccessor httpContextAccessor, UserDataService userDataService)
    {
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;
        _userDataService = userDataService;
    }

    public async Task<ClientsideFriendsImportResponse> ExecuteAsync(ClientsideFriendsImportRequest request)
    {
        var context = _httpContextAccessor.HttpContext;
        if (context == null)
        {
            throw new CloudScriptException("CloudScript was not called within a http request");
        }
        var userId = context.User.FindAuthUserId();

        // Persist the platform friend ids the client imports (Steam ids) so GetFriendList
        // can later resolve which of them actually play on this server.
        var ids = request.UserIDs ?? Array.Empty<string>();
        await _userDataService.UpdateAsync(userId, userId, new Dictionary<string, string>
        {
            ["ImportedSteamFriends"] = JsonSerializer.Serialize(ids),
        });
        _logger.LogInformation("Imported {Count} {Platform} friend id(s) for user {User}", ids.Length, request.Platform, userId);

        return new ClientsideFriendsImportResponse{};
    }
}
