// 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 Catalogger.Backend.Database.Repositories;
using Catalogger.Backend.Extensions;
using Catalogger.Backend.Services;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.Extensions.Embeds;
using Remora.Discord.Gateway.Responders;
using Remora.Results;

namespace Catalogger.Backend.Bot.Responders.Channels;

public class ChannelDeleteResponder(
    ILogger logger,
    GuildRepository guildRepository,
    ChannelCache channelCache,
    WebhookExecutorService webhookExecutor
) : IResponder<IChannelDelete>
{
    private readonly ILogger _logger = logger.ForContext<ChannelDeleteResponder>();

    public async Task<Result> RespondAsync(IChannelDelete evt, CancellationToken ct = default)
    {
        if (!evt.GuildID.IsDefined())
        {
            _logger.Debug("Deleted channel {ChannelId} is not in a guild", evt.ID);
            return Result.Success;
        }

        if (!channelCache.TryGet(evt.ID, out var channel))
        {
            _logger.Information("Deleted channel {ChannelId} not found in the cache", evt.ID);
            channelCache.Remove(evt.GuildID.OrDefault(), evt.ID, out _);
            return Result.Success;
        }

        var guildConfig = await guildRepository.GetAsync(evt.GuildID.Value);
        var embed = new EmbedBuilder()
            .WithTitle("Channel deleted")
            .WithColour(DiscordUtils.Red)
            .WithFooter($"ID: {evt.ID}")
            .WithCurrentTimestamp()
            .WithDescription($"**Name:** {channel.Name.Value}");

        if (
            channel.ParentID.IsDefined(out var parentId)
            && channelCache.TryGet(parentId.Value, out var category)
        )
            embed.Description += $"\n**Category:** {category.Name}";
        else
            embed.Description += "\n**Category:** (none)";

        if (channel.Topic.IsDefined(out var topic))
            embed.AddField("Description", topic);

        webhookExecutor.QueueLog(
            webhookExecutor.GetLogChannel(
                guildConfig,
                LogChannelType.ChannelDelete,
                channelId: channel.ID
            ),
            embed.Build().GetOrThrow()
        );
        return Result.Success;
    }
}
