package handlers

import (
	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

func GetOwnProfile(c *fiber.Ctx) error {
	userID, ok := c.Locals("user_id").(uuid.UUID)
	if !ok {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
			"error": "Authentication required",
		})
	}

	var user models.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
			"error": "User not found",
		})
	}

	var activeBans []models.Ban
	database.DB.Where("user_id = ? AND revoked = false AND type != ? AND (expires_at IS NULL OR expires_at > NOW())",
		userID, models.BanTypeWarning).Find(&activeBans)

	for i := range activeBans {
		activeBans[i].InternalNote = nil
		activeBans[i].Evidence = nil
	}

	var mmrHistory []models.MMRHistory
	database.DB.Where("user_id = ?", userID).
		Order("created_at DESC").
		Limit(20).
		Find(&mmrHistory)

	penalty := models.Penalty{}
	var activePenalty *models.Penalty
	if err := database.DB.Where("user_id = ? AND expires_at > NOW()", userID).
		Order("expires_at DESC").First(&penalty).Error; err == nil {
		activePenalty = &penalty
	}

	response := fiber.Map{
		"id":                 user.ID,
		"username":           user.Username,
		"email":              user.Email,
		"steam_id":           user.SteamID,
		"steam_persona_name": user.SteamPersonaName,
		"steam_avatar_url":   user.SteamAvatarURL,
		"steam_linked_at":    user.SteamLinkedAt,
		"role":               user.Role,
		"tier":               user.Tier,
		"tier_expires_at":    user.TierExpiresAt,
		"profile_banner":     user.ProfileBanner,
		"mmr":                user.MMR,
		"wins":               user.Wins,
		"losses":             user.Losses,
		"matches_played":     user.MatchesPlayed,
		"current_streak":     user.CurrentStreak,
		"last_match_at":      user.LastMatchAt,
		"placement_done":     user.PlacementDone,
		"created_at":         user.CreatedAt,
		"active_bans":        activeBans,
		"mmr_history":        mmrHistory,
		"active_penalty":     activePenalty,
	}

	return c.JSON(response)
}

func GetPublicProfile(c *fiber.Ctx) error {
	username := c.Params("username")
	if username == "" {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "Username is required",
		})
	}

	var user models.User
	if err := database.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
			"error": "User not found",
		})
	}

	profile := user.ToPublicProfile()

	var activeBanCount int64
	database.DB.Model(&models.Ban{}).
		Where("user_id = ? AND revoked = false AND type != ? AND (expires_at IS NULL OR expires_at > NOW())",
			user.ID, models.BanTypeWarning).
		Count(&activeBanCount)

	response := fiber.Map{
		"profile":   profile,
		"is_banned": activeBanCount > 0,
	}

	var recentMatches []models.MatchPlayer
	database.DB.Where("user_id = ?", user.ID).
		Preload("User").
		Order("id DESC").
		Limit(10).
		Find(&recentMatches)

	var mmrHistory []models.MMRHistory
	database.DB.Where("user_id = ?", user.ID).
		Order("created_at DESC").
		Limit(20).
		Find(&mmrHistory)

	response["mmr_history"] = mmrHistory

	return c.JSON(response)
}
