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

namespace Catalogger.Backend.Bot.Responders.Invites;

public class InviteCreateResponder(
    ILogger logger,
    GuildRepository guildRepository,
    IInviteCache inviteCache,
    IDiscordRestGuildAPI guildApi,
    WebhookExecutorService webhookExecutor
) : IResponder<IInviteCreate>
{
    private readonly ILogger _logger = logger.ForContext<InviteCreateResponder>();

    public async Task<Result> RespondAsync(IInviteCreate evt, CancellationToken ct = default)
    {
        var guildId = evt.GuildID.Value;

        var invitesResult = await guildApi.GetGuildInvitesAsync(guildId, ct);
        if (!invitesResult.IsSuccess)
        {
            _logger.Error(
                "Error fetching new invites for guild {GuildId}: {Error}",
                guildId,
                invitesResult.Error
            );
        }
        else
        {
            await inviteCache.SetAsync(guildId, invitesResult.Entity);
        }

        var embed = new EmbedBuilder()
            .WithTitle("Invite created")
            .WithDescription($"A new invite (**{evt.Code}**) was created for <#{evt.ChannelID}>.")
            .WithColour(DiscordUtils.Green)
            .WithFooter($"Code: {evt.Code}");

        embed.AddField("Created by", evt.Inviter.GetOrThrow().PrettyFormat());
        embed.AddField(
            "Maximum uses",
            evt.MaxUses != 0 ? evt.MaxUses.ToString() : "Infinite",
            inline: true
        );
        embed.AddField(
            "Expires",
            evt.MaxAge == TimeSpan.Zero
                ? "Never"
                : $"<t:{(DateTimeOffset.UtcNow + evt.MaxAge).ToUnixTimeSeconds()}>",
            inline: true
        );

        var guildConfig = await guildRepository.GetAsync(evt.GuildID);
        webhookExecutor.QueueLog(
            guildConfig,
            LogChannelType.InviteCreate,
            embed.Build().GetOrThrow()
        );
        return Result.Success;
    }
}
