package config

import (
	"context"
	"strconv"

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

	"github.com/bwmarrin/discordgo"
)

func slvlSetLevelOption() *discordgo.ApplicationCommandOption {
	return &discordgo.ApplicationCommandOption{
		Type:        discordgo.ApplicationCommandOptionSubCommand,
		Name:        "set",
		Description: "Set the level of a user",
		Options: []*discordgo.ApplicationCommandOption{
			{
				Type:        discordgo.ApplicationCommandOptionUser,
				Name:        "user",
				Description: "The user to set the level of",
				Required:    true,
			},
			{
				Type:        discordgo.ApplicationCommandOptionInteger,
				Name:        "level",
				Description: "The level to set the user to",
				Required:    true,
			},
		},
	}
}

func slvlSetLevelHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !shared.RequireManageGuild(s, i) || !shared.RequireLevelSystemEnabled(s, i) {
		return
	}
	if services.Global == nil || services.Global.Level == nil {
		shared.RespondEphemeral(s, i, "Leveling service is not available.")
		return
	}

	optMap := shared.SubcommandOptionMap(i)
	userOpt, ok := optMap["user"]
	if !ok {
		shared.RespondEphemeral(s, i, "Missing user option.")
		return
	}
	levelOpt, ok := optMap["level"]
	if !ok {
		shared.RespondEphemeral(s, i, "Missing level option.")
		return
	}

	targetUser := userOpt.UserValue(s)
	if targetUser == nil {
		shared.RespondEphemeral(s, i, "Invalid user.")
		return
	}
	if targetUser.Bot {
		shared.RespondEphemeral(s, i, "You can't set a bot's level.")
		return
	}

	newLevel := int(levelOpt.IntValue())
	guildID, ok := shared.ParseGuildID(s, i)
	if !ok {
		return
	}
	userID, err := strconv.ParseInt(targetUser.ID, 10, 64)
	if err != nil {
		shared.RespondEphemeral(s, i, "Invalid user ID.")
		return
	}

	if err := services.Global.Level.SetLevel(context.Background(), guildID, userID, newLevel); err != nil {
		shared.RespondEphemeral(s, i, "Failed to set level.")
		return
	}

	shared.RespondEphemeral(s, i, "Level set to "+strconv.Itoa(newLevel)+" for "+targetUser.Mention()+".")
}

