package services

import (
	"time"

	"github.com/google/uuid"
	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

// GetActiveBan returns the most severe active ban for a user, or nil if none.
// Warnings are excluded because they don't restrict the user.
func GetActiveBan(userID uuid.UUID) *models.Ban {
	var ban models.Ban
	now := time.Now().UTC()

	err := database.DB.
		Where("user_id = ? AND revoked = false AND type != ?", userID, models.BanTypeWarning).
		Where("expires_at IS NULL OR expires_at > ?", now).
		Order("CASE type WHEN 'full' THEN 1 WHEN 'perm' THEN 2 WHEN 'game' THEN 3 WHEN 'temp' THEN 4 ELSE 5 END").
		First(&ban).Error
	if err != nil {
		return nil
	}
	return &ban
}

func HasActiveGameBan(userID uuid.UUID) *models.Ban {
	var ban models.Ban
	now := time.Now().UTC()

	err := database.DB.
		Where("user_id = ? AND revoked = false AND type IN (?, ?, ?, ?)",
			userID, models.BanTypeFull, models.BanTypePerm, models.BanTypeGame, models.BanTypeTemp).
		Where("expires_at IS NULL OR expires_at > ?", now).
		First(&ban).Error
	if err != nil {
		return nil
	}
	return &ban
}

func HasActivePenalty(userID uuid.UUID) *models.Penalty {
	var penalty models.Penalty
	now := time.Now().UTC()

	err := database.DB.
		Where("user_id = ? AND expires_at > ?", userID, now).
		Order("expires_at DESC").
		First(&penalty).Error
	if err != nil {
		return nil
	}
	return &penalty
}

func GetPenaltyCount(userID uuid.UUID) int64 {
	var count int64
	weekAgo := time.Now().UTC().Add(-7 * 24 * time.Hour)
	database.DB.Model(&models.Penalty{}).
		Where("user_id = ? AND created_at > ?", userID, weekAgo).
		Count(&count)
	return count
}

func CooldownDuration(offenseCount int64) time.Duration {
	switch {
	case offenseCount <= 0:
		return 30 * time.Minute
	case offenseCount == 1:
		return 2 * time.Hour
	case offenseCount == 2:
		return 24 * time.Hour
	default:
		return 7 * 24 * time.Hour
	}
}
