package lib

import (
	"time"

	"github.com/bwmarrin/discordgo"
)

type CommandFunc func(s *discordgo.Session, i *discordgo.InteractionCreate) (string, error)

func HandleCommand(commandName string, cooldownDuration time.Duration, handler CommandFunc) func(s *discordgo.Session, i *discordgo.InteractionCreate) {
	return func(s *discordgo.Session, i *discordgo.InteractionCreate) {
		if !CheckAndApplyCooldown(s, i, commandName, cooldownDuration) {
			return
		}

		// Get user information (handle both guild and DM contexts)
		user, userErr := GetUser(i)
		if userErr != nil {
			RespondWithError(s, i, "Error getting user information: "+userErr.Error())
			return
		}

		// Get or create user and guild profile
		_, createUserError := GetOrCreateUserWithGuild(user.ID, user.Username, i.GuildID)

		if createUserError != nil {
			RespondWithError(s, i, "Error creating user profile: "+createUserError.Error())
			return
		}

		// Acknowledge the interaction immediately
		interactErr := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
		})

		if interactErr != nil {
			ThrowWithError(commandName, "Error deferring response: "+interactErr.Error())
			return
		}

		// Execute the command handler
		response, handlerErr := handler(s, i)

		if handlerErr != nil {
			RespondWithError(s, i, "Error processing command: "+handlerErr.Error())
			return
		}

		// Send the follow-up message with the response
		_, followErr := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
			Content: response,
		})

		if followErr != nil {
			ThrowWithError(commandName, "Error sending follow-up message: "+followErr.Error())
		}
	}
}
