package public

import (
	"bytes"
	"context"
	"strconv"

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

	"github.com/bwmarrin/discordgo"
)

var Rank = &discordgo.ApplicationCommand{
	Name:        "rank",
	Description: "Get your level card",
	Options: []*discordgo.ApplicationCommandOption{
		{
			Type:        discordgo.ApplicationCommandOptionUser,
			Name:        "user",
			Description: "The user to get the rank card of",
			Required:    false,
		},
	},
}

func RankHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !shared.RequireLevelServices(s, i) {
		return
	}
	if i.GuildID != "" && !shared.RequireLevelSystemEnabled(s, i) {
		return
	}

	// Determine target user: option or caller.
	target := i.User
	if i.Member != nil && i.Member.User != nil {
		target = i.Member.User
	}
	if len(i.ApplicationCommandData().Options) > 0 {
		if u := i.ApplicationCommandData().Options[0].UserValue(s); u != nil {
			target = u
		}
	}
	if target == nil {
		return
	}

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

	ctx := context.Background()
	lvl, err := services.Global.Level.GetLevel(ctx, guildID, userID)
	if err != nil {
		shared.RespondEphemeral(s, i, "Failed to load level.")
		return
	}

	percent := float64(lvl.XP) / 100.0
	avatarURL := target.AvatarURL("256")

	pngBytes, err := rankcard.RenderPNG(ctx, rankcard.Data{
		Name:    target.Username,
		Level:   lvl.Level,
		XP:      lvl.XP,
		Percent: percent,
		Avatar:  avatarURL,
	})
	if err != nil {
		shared.RespondEphemeral(s, i, "Failed to render rank card.")
		return
	}

	_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Files: []*discordgo.File{
				{
					Name:   "levelcard.png",
					Reader: bytes.NewReader(pngBytes),
				},
			},
		},
	})
}

