package middlewares

import (
	"os"

	"github.com/gofiber/fiber/v2"
)

// InternalKeyAuth guards machine-to-machine endpoints with a static API key.
// The key is read from INTERNAL_API_KEY env var at request time so it can be
// rotated without redeployment. Returns 401 if the header is missing or wrong.
func InternalKeyAuth(c *fiber.Ctx) error {
	expected := os.Getenv("INTERNAL_API_KEY")
	if expected == "" || c.Get("X-Internal-Key") != expected {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
			"success": false,
			"message": "unauthorized",
		})
	}
	return c.Next()
}
