package config

import (
	"context"
	"strconv"

	"velox-bot/internal/commands/level/shared"
	"velox-bot/internal/db/services"

	"github.com/bwmarrin/discordgo"
)

func slvlSetChannelOption() *discordgo.ApplicationCommandOption {
	return &discordgo.ApplicationCommandOption{
		Type:        discordgo.ApplicationCommandOptionSubCommand,
		Name:        "set-channel",
		Description: "Set the level up channel",
		Options: []*discordgo.ApplicationCommandOption{
			{
				Type:        discordgo.ApplicationCommandOptionChannel,
				Name:        "channel",
				Description: "Channel for level-up messages",
				Required:    true,
			},
		},
	}
}

func slvlSetChannelHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !shared.RequireManageGuild(s, i) || !shared.RequireLevelSystemEnabled(s, i) {
		return
	}
	if !shared.RequireLevelSettingsService(s, i) {
		return
	}

	guildID, ok := shared.ParseGuildID(s, i)
	if !ok {
		return
	}

	optMap := shared.SubcommandOptionMap(i)
	channelOpt, ok := optMap["channel"]
	if !ok {
		shared.RespondEphemeral(s, i, "Missing channel option.")
		return
	}

	ch := channelOpt.ChannelValue(s)
	if ch == nil {
		shared.RespondEphemeral(s, i, "Invalid channel.")
		return
	}

	channelID, err := strconv.ParseInt(ch.ID, 10, 64)
	if err != nil {
		shared.RespondEphemeral(s, i, "Invalid channel ID.")
		return
	}

	if err := services.Global.LevelSettings.SetLevelUpChannel(context.Background(), guildID, channelID); err != nil {
		shared.RespondEphemeral(s, i, "Failed to set level up channel.")
		return
	}

	shared.RespondEphemeral(s, i, "Level up channel set to "+ch.Mention()+".")
}

