// 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 Microsoft.Extensions.Logging.Configuration;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.Extensions.Embeds;
using Remora.Discord.Gateway.Responders;
using Remora.Results;

namespace Catalogger.Backend.Bot.Responders.Channels;

public class ChannelCreateResponder(
    GuildRepository guildRepository,
    RoleCache roleCache,
    ChannelCache channelCache,
    UserCache userCache,
    WebhookExecutorService webhookExecutor
) : IResponder<IChannelCreate>
{
    public async Task<Result> RespondAsync(IChannelCreate ch, CancellationToken ct = default)
    {
        if (!ch.GuildID.IsDefined())
            return Result.Success;
        channelCache.Set(ch);

        var builder = new EmbedBuilder()
            .WithTitle(
                ch.Type switch
                {
                    ChannelType.GuildVoice => "Voice channel created",
                    ChannelType.GuildCategory => "Category channel created",
                    ChannelType.GuildAnnouncement or ChannelType.GuildText =>
                        "Text channel created",
                    _ => "Channel created",
                }
            )
            .WithColour(DiscordUtils.Green)
            .WithFooter($"ID: {ch.ID}");

        if (ch.ParentID.IsDefined(out var parentId))
        {
            builder.WithDescription(
                channelCache.TryGet(parentId.Value, out var parentChannel)
                    ? $"**Name:** {ch.Name}\n**Category:** {parentChannel.Name}"
                    : $"**Name:** {ch.Name}"
            );
        }
        else
            builder.WithDescription($"**Name:** {ch.Name}");

        foreach (var overwrite in ch.PermissionOverwrites.OrDefault() ?? [])
        {
            if (overwrite.Type == PermissionOverwriteType.Role)
            {
                var roleName = roleCache.TryGet(overwrite.ID, out var role)
                    ? role.Name
                    : $"role {overwrite.ID}";
                var embedFieldValue = "";
                if (overwrite.Allow.GetPermissions().Count != 0)
                    embedFieldValue += $"\u2705 {overwrite.Allow.ToPrettyString()}";
                if (overwrite.Deny.GetPermissions().Count != 0)
                    embedFieldValue += $"\n\n\u274c {overwrite.Deny.ToPrettyString()}";

                builder.AddField($"Override for {roleName}", embedFieldValue.Trim());
            }
            else
            {
                var user = await userCache.GetUserAsync(overwrite.ID);
                var embedFieldValue = "";
                if (overwrite.Allow.GetPermissions().Count != 0)
                    embedFieldValue += $"\u2705 {overwrite.Allow.ToPrettyString()}";
                if (overwrite.Deny.GetPermissions().Count != 0)
                    embedFieldValue += $"\n\n\u274c {overwrite.Deny.ToPrettyString()}";

                builder.AddField(
                    $"Override for {user?.Tag() ?? $"user {overwrite.ID}"}",
                    embedFieldValue.Trim()
                );
            }
        }

        var guildConfig = await guildRepository.GetAsync(ch.GuildID);
        webhookExecutor.QueueLog(
            webhookExecutor.GetLogChannel(
                guildConfig,
                LogChannelType.ChannelCreate,
                channelId: ch.ID
            ),
            builder.Build().GetOrThrow()
        );
        return Result.Success;
    }
}
