// 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.InMemoryCache;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.Gateway.Responders;
using Remora.Results;

namespace Catalogger.Backend.Bot.Responders.Guilds;

public class AuditLogResponder(AuditLogCache auditLogCache, ILogger logger)
    : IResponder<IGuildAuditLogEntryCreate>
{
    private readonly ILogger _logger = logger.ForContext<AuditLogResponder>();

    public Task<Result> RespondAsync(IGuildAuditLogEntryCreate evt, CancellationToken ct = default)
    {
        if (evt.TargetID == null || evt.UserID == null)
            return Task.FromResult(Result.Success);

        switch (evt.ActionType)
        {
            case AuditLogEvent.MemberKick:
                auditLogCache.SetKick(evt.GuildID, evt.TargetID, evt.UserID.Value, evt.Reason);
                break;
            case AuditLogEvent.MemberBanAdd:
                auditLogCache.SetBan(evt.GuildID, evt.TargetID, evt.UserID.Value, evt.Reason);
                break;
            case AuditLogEvent.MemberBanRemove:
                auditLogCache.SetUnban(evt.GuildID, evt.TargetID, evt.UserID.Value, evt.Reason);
                break;
            case AuditLogEvent.MemberRoleUpdate:
            case AuditLogEvent.MemberUpdate:
                auditLogCache.SetMemberUpdate(
                    evt.GuildID,
                    evt.TargetID,
                    evt.UserID.Value,
                    evt.Reason
                );
                break;
            default:
                _logger.Debug(
                    "Received audit log event {Id} with type {Type} that we don't care about, ignoring",
                    evt.ID,
                    evt.ActionType
                );
                break;
        }

        return Task.FromResult(Result.Success);
    }
}
