package public

import (
	"context"
	"fmt"

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

	"github.com/bwmarrin/discordgo"
)

var Rewards = &discordgo.ApplicationCommand{
	Name:        "rewards",
	Description: "View level rewards in this server",
}

func RewardsHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !shared.RequireGuild(s, i) {
		return
	}
	if !shared.RequireLevelSettingsService(s, i) {
		return
	}
	if !shared.RequireLevelSystemEnabled(s, i) {
		return
	}

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

	ctx := context.Background()
	rewards, err := services.Global.LevelSettings.ListRoleRewards(ctx, guildID, 25)
	if err != nil {
		shared.RespondEphemeral(s, i, "Failed to load rewards.")
		return
	}
	if len(rewards) == 0 {
		shared.RespondEphemeral(s, i, "No rewards configured yet.")
		return
	}

	fields := make([]*discordgo.MessageEmbedField, 0, len(rewards))
	for _, r := range rewards {
		fields = append(fields, &discordgo.MessageEmbedField{
			Name:   fmt.Sprintf("Level %d", r.Level),
			Value:  fmt.Sprintf("<@&%d>", r.RoleID),
			Inline: true,
		})
	}

	embed := &discordgo.MessageEmbed{
		Title:       "Level Rewards",
		Description: "Roles granted when you reach a level.",
		Fields:      fields,
		Color:       0xF59E0B,
	}

	_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Embeds: []*discordgo.MessageEmbed{embed},
		},
	})
}

