package handlers

import (
	"github.com/bwmarrin/discordgo"
	"kleincordBot/services"
	"strconv"
)

func DeleteCommand(data discordgo.ApplicationCommandInteractionData, s *discordgo.Session, i *discordgo.InteractionCreate) {
	amount, _ := strconv.Atoi(data.Options[0].Value.(string))
	if amount > 100 {
		amount = 100
	}
	messages, err := s.ChannelMessages(i.ChannelID, amount, "", "", "")
	if err != nil {
		return
	}
	err = s.InteractionRespond(
		i.Interaction,
		&discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "deleting " + strconv.Itoa(len(messages)) + " messages",
			},
		},
	)
	if err != nil {
		// Handle the error
	}
	for _, message := range messages {
		var Webhooks []*discordgo.Webhook
		Webhooks, err = s.ChannelWebhooks(i.ChannelID)
		OnlyWebhook, _ := strconv.ParseBool(data.Options[1].Value.(string))
		if OnlyWebhook {
			for _, Webhook := range Webhooks {
				if message.Author.ID == Webhook.ID {
					s.ChannelMessageDelete(i.ChannelID, message.ID)
					println(message.Content + " deleted")
				}
			}
		} else {
			s.ChannelMessageDelete(i.ChannelID, message.ID)
			println(message.Content + " deleted")
		}
	}
	_, err = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
		Content: strconv.Itoa(len(messages)) + " Message deleted",
	})
	if err != nil {
		services.HandleError(err, s)
	}
}
