// Copyright (C) 2021-present sam (starshines.gay)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

using Catalogger.Backend.Cache;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.Gateway.Responders;
using Remora.Results;

namespace Catalogger.Backend.Bot.Responders.Guilds;

public class GuildMembersChunkResponder(ILogger logger, IMemberCache memberCache)
    : IResponder<IGuildMembersChunk>
{
    private readonly ILogger _logger = logger.ForContext<GuildMembersChunkResponder>();

    public async Task<Result> RespondAsync(IGuildMembersChunk evt, CancellationToken ct = default)
    {
        _logger.Debug(
            "Received chunk {ChunkIndex} / {ChunkCount} for guild {GuildId}",
            evt.ChunkIndex + 1,
            evt.ChunkCount,
            evt.GuildID
        );

        await memberCache.SetManyAsync(evt.GuildID, evt.Members);
        await memberCache.SetMemberNamesAsync(evt.GuildID, evt.Members);

        if (evt.ChunkIndex == evt.ChunkCount - 1)
        {
            _logger.Debug(
                "Final chunk for guild {GuildId} received, marking as cached",
                evt.GuildID
            );
            await memberCache.MarkAsCachedAsync(evt.GuildID);
        }

        return Result.Success;
    }
}
