package bot

import (
	"fmt"

	"github.com/bwmarrin/discordgo"
)

var registeredCommands = []*discordgo.ApplicationCommand{
	{
		Name:        "ping",
		Description: "Ping a server to make sure it's still online.",
		Options: []*discordgo.ApplicationCommandOption{
			{
				Type:        discordgo.ApplicationCommandOptionString,
				Name:        "host",
				Description: "The server hostname or IP to ping",
				Required:    true,
			},
		},
	},
	// future commands can be added here
}

func registerCommands(s *discordgo.Session) {
	existing, err := s.ApplicationCommands(s.State.User.ID, "")
	if err != nil {
		fmt.Println("Failed to list existing commands:", err)
		return
	}

	for _, cmd := range registeredCommands {
		alreadyExists := false
		for _, e := range existing {
			if e.Name == cmd.Name {
				alreadyExists = true
				break
			}
		}

		if alreadyExists {
			fmt.Printf("Command '%s' already exists, skipping registration.\n", cmd.Name)
			continue
		}

		_, err := s.ApplicationCommandCreate(s.State.User.ID, "", cmd)
		if err != nil {
			fmt.Printf("Cannot create command '%s': %v\n", cmd.Name, err)
		} else {
			fmt.Printf("Registered command: %s\n", cmd.Name)
		}
	}
}

// Cleanup commands on shutdown
func cleanupCommands(s *discordgo.Session) {
	commands, err := s.ApplicationCommands(s.State.User.ID, "")
	if err != nil {
		return
	}
	for _, cmd := range commands {
		_ = s.ApplicationCommandDelete(s.State.User.ID, "", cmd.ID)
	}
}
