package config

import (
	"context"
	"strconv"

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

	"github.com/bwmarrin/discordgo"
)

func slvlSetRewardOption() *discordgo.ApplicationCommandOption {
	return &discordgo.ApplicationCommandOption{
		Type:        discordgo.ApplicationCommandOptionSubCommand,
		Name:        "set-reward",
		Description: "Set role reward for a level",
		Options: []*discordgo.ApplicationCommandOption{
			{
				Type:        discordgo.ApplicationCommandOptionInteger,
				Name:        "level",
				Description: "Level to reward",
				Required:    true,
			},
			{
				Type:        discordgo.ApplicationCommandOptionRole,
				Name:        "role",
				Description: "Role to grant",
				Required:    true,
			},
		},
	}
}

func slvlSetRewardHandler(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)
	levelOpt, ok := optMap["level"]
	if !ok {
		shared.RespondEphemeral(s, i, "Missing level option.")
		return
	}
	roleOpt, ok := optMap["role"]
	if !ok {
		shared.RespondEphemeral(s, i, "Missing role option.")
		return
	}

	level := int(levelOpt.IntValue())
	role := roleOpt.RoleValue(s, i.GuildID)
	if role == nil {
		shared.RespondEphemeral(s, i, "Invalid role.")
		return
	}
	roleID, err := strconv.ParseInt(role.ID, 10, 64)
	if err != nil {
		shared.RespondEphemeral(s, i, "Invalid role ID.")
		return
	}

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

	shared.RespondEphemeral(s, i, "Reward set: level "+strconv.Itoa(level)+" -> "+role.Mention())
}

