package middleware

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

// BanCheck rejects requests from users with an active full ban. Other ban
// types only block specific actions; handlers check those themselves.
func BanCheck() fiber.Handler {
	return func(c *fiber.Ctx) error {
		userID, ok := c.Locals("user_id").(uuid.UUID)
		if !ok {
			return c.Next()
		}

		ban := services.GetActiveBan(userID)
		if ban == nil {
			return c.Next()
		}

		if ban.Type == "full" {
			resp := fiber.Map{
				"error":   "Your account has been banned",
				"reason":  ban.Reason,
				"type":    ban.Type,
				"banned":  true,
			}
			if ban.ExpiresAt != nil {
				resp["expires_at"] = ban.ExpiresAt
			}
			return c.Status(fiber.StatusForbidden).JSON(resp)
		}

		c.Locals("active_ban", ban)
		return c.Next()
	}
}

func InternalAuth(apiSecret string) fiber.Handler {
	return func(c *fiber.Ctx) error {
		auth := c.Get("Authorization")
		if auth != "Bearer "+apiSecret {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "Invalid internal API secret",
			})
		}
		return c.Next()
	}
}
