// 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 Microsoft.Extensions.Options;
using Remora.Commands.Services;
using Remora.Commands.Tokenization;
using Remora.Commands.Trees;
using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.API.Abstractions.Rest;
using Remora.Discord.Commands.Responders;
using Remora.Discord.Commands.Services;
using Remora.Discord.Gateway.Responders;
using Remora.Results;

namespace Catalogger.Backend.Bot.Responders;

/// <summary>
/// Wrapper for Remora.Discord's default interaction responder, that ignores all events if test mode is enabled.
/// </summary>
public class CustomInteractionResponder(
    Config config,
    ILogger logger,
    CommandService commandService,
    IOptions<InteractionResponderOptions> options,
    IDiscordRestInteractionAPI interactionAPI,
    ExecutionEventCollectorService eventCollector,
    IServiceProvider services,
    ContextInjectionService contextInjection,
    IOptions<TokenizerOptions> tokenizerOptions,
    IOptions<TreeSearchOptions> treeSearchOptions,
    ITreeNameResolver? treeNameResolver = null
) : IResponder<IInteractionCreate>
{
    private readonly ILogger _logger = logger.ForContext<CustomInteractionResponder>();

    private readonly InteractionResponder _inner =
        new(
            commandService,
            options,
            interactionAPI,
            eventCollector,
            services,
            contextInjection,
            tokenizerOptions,
            treeSearchOptions,
            treeNameResolver
        );

    public async Task<Result> RespondAsync(
        IInteractionCreate gatewayEvent,
        CancellationToken ct = default
    )
    {
        if (config.Discord.TestMode)
        {
            _logger.Information(
                "Not responding to interaction create event {InteractionId} in {ChannelId} as test mode is enabled",
                gatewayEvent.ID,
                gatewayEvent.Channel.Map(c => c.ID).OrDefault()
            );
            return Result.Success;
        }

        return await _inner.RespondAsync(gatewayEvent, ct);
    }
}
