package public

import (
	"context"
	"fmt"
	"strconv"

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

	"github.com/bwmarrin/discordgo"
)

var Leaderboard = &discordgo.ApplicationCommand{
	Name:        "leaderboard",
	Description: "Top 10 levels in this server",
}

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

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

	ctx := context.Background()
	top, err := services.Global.Level.TopLevels(ctx, guildID, 10)
	if err != nil {
		shared.RespondEphemeral(s, i, "Failed to load leaderboard.")
		return
	}
	if len(top) == 0 {
		shared.RespondEphemeral(s, i, "No leaderboard data yet.")
		return
	}

	fields := make([]*discordgo.MessageEmbedField, 0, len(top))
	for idx, entry := range top {
		display := fmt.Sprintf("<@%d>", entry.UserID)
		if u, err := s.User(strconv.FormatInt(entry.UserID, 10)); err == nil && u != nil && u.Username != "" {
			display = u.Username
		}
		fields = append(fields, &discordgo.MessageEmbedField{
			Name:   fmt.Sprintf("%d. %s", idx+1, display),
			Value:  fmt.Sprintf("Level: **%d** | XP: **%d**", entry.Level, entry.XP),
			Inline: false,
		})
	}

	embed := &discordgo.MessageEmbed{
		Title:       "Leaderboard",
		Description: fmt.Sprintf("These are the top %d users in the server", len(top)),
		Fields:      fields,
		Color:       0xF59E0B,
	}

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

