using Application.Abstractions.Cache;
using Application.Abstractions.Chat;
using StackExchange.Redis;
using System.Text.Json;

namespace Infrastructure.Chat;

public class RedisChatMessageStore(IConnectionMultiplexer redis) : IChatMessageStore
{
    private readonly IDatabase _db = redis.GetDatabase();

    private static readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = false
    };




    public async Task AddMessageAsync(ChatMessage message)
    {
        var json = JsonSerializer.Serialize(message, _jsonOptions);

        await _db.ListLeftPushAsync(CacheKeys.ChatGlobalMessages, json);

        await _db.ListTrimAsync(CacheKeys.ChatGlobalMessages, 0, ChatSettings.MaxMessages - 1);
    }

    public async Task<IReadOnlyList<ChatMessage>> GetRecentMessagesAsync(int count)
    {
        var values = await _db.ListRangeAsync(CacheKeys.ChatGlobalMessages, 0, count - 1);
        if (values.Length <= 0)
        {
            return [];
        }

        var messages = new List<ChatMessage>(values.Length);

        foreach (var row in values)
        {
            if (!row.IsNullOrEmpty)
            {
                var message = JsonSerializer.Deserialize<ChatMessage>((string)row!, _jsonOptions);
                if (message is not null)
                {
                    messages.Add(message);
                }
            }
        }

        messages.Reverse();
        return messages;
    }
}