// 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 OneOf;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Abstractions.Rest;
using Remora.Discord.API.Objects;
using Remora.Discord.Commands.Feedback.Messages;
using Remora.Discord.Commands.Feedback.Services;
using Remora.Rest.Core;
using Remora.Results;

namespace Catalogger.Backend.Extensions;

public static class DiscordRestExtensions
{
    public static async Task<Result> UpdateMessageAsync(
        this IDiscordRestInteractionAPI interactionApi,
        IInteraction interaction,
        InteractionMessageCallbackData data
    ) =>
        await interactionApi.CreateInteractionResponseAsync(
            interaction.ID,
            interaction.Token,
            new InteractionResponse(
                InteractionCallbackType.UpdateMessage,
                new Optional<
                    OneOf<
                        IInteractionMessageCallbackData,
                        IInteractionAutocompleteCallbackData,
                        IInteractionModalCallbackData
                    >
                >(data)
            )
        );

    public static async Task<Result<IMessage>> ReplyAsync(
        this IFeedbackService feedbackService,
        Optional<string> content = default,
        IEnumerable<IEmbed>? embeds = null,
        bool isEphemeral = false
    ) =>
        await feedbackService.SendContextualAsync(
            content,
            embeds != null
                ? new Optional<IReadOnlyList<IEmbed>>(embeds.ToList())
                : new Optional<IReadOnlyList<IEmbed>>(),
            options: new FeedbackMessageOptions(
                MessageFlags: isEphemeral ? MessageFlags.Ephemeral : 0,
                AllowedMentions: new AllowedMentions(
                    Parse: new List<MentionType>(),
                    MentionRepliedUser: true
                )
            )
        );
}
