package handlers

import (
	"strconv"

	"github.com/gofiber/fiber/v2"
	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

func GetLeaderboard(c *fiber.Ctx) error {
	page, _ := strconv.Atoi(c.Query("page", "1"))
	limit, _ := strconv.Atoi(c.Query("limit", "50"))
	if page < 1 {
		page = 1
	}
	if limit < 1 || limit > 100 {
		limit = 50
	}
	offset := (page - 1) * limit

	var total int64
	database.DB.Model(&models.User{}).Where("placement_done = true").Count(&total)

	var users []models.User
	database.DB.Where("placement_done = true").
		Order("mmr DESC").
		Offset(offset).
		Limit(limit).
		Find(&users)

	type leaderboardEntry struct {
		Rank             int     `json:"rank"`
		ID               string  `json:"id"`
		Username         string  `json:"username"`
		SteamAvatarURL   *string `json:"steam_avatar_url,omitempty"`
		SteamPersonaName *string `json:"steam_persona_name,omitempty"`
		Role             string  `json:"role"`
		Tier             string  `json:"tier"`
		MMR              int     `json:"mmr"`
		Wins             int     `json:"wins"`
		Losses           int     `json:"losses"`
		MatchesPlayed    int     `json:"matches_played"`
		WinRate          float64 `json:"win_rate"`
	}

	entries := make([]leaderboardEntry, len(users))
	for i, u := range users {
		var winRate float64
		if u.MatchesPlayed > 0 {
			winRate = float64(u.Wins) / float64(u.MatchesPlayed) * 100
		}
		entries[i] = leaderboardEntry{
			Rank:             offset + i + 1,
			ID:               u.ID.String(),
			Username:         u.Username,
			SteamAvatarURL:   u.SteamAvatarURL,
			SteamPersonaName: u.SteamPersonaName,
			Role:             u.Role,
			Tier:             u.Tier,
			MMR:              u.MMR,
			Wins:             u.Wins,
			Losses:           u.Losses,
			MatchesPlayed:    u.MatchesPlayed,
			WinRate:          winRate,
		}
	}

	return c.JSON(fiber.Map{
		"players": entries,
		"total":   total,
		"page":    page,
		"limit":   limit,
	})
}
