package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"switchboard-core/storage"
)

// storageConfigured is a package-level flag set during init.
// Read by PublicSettings to include in the boot payload.
var storageConfigured bool

// SetStorageConfigured sets the package-level flag indicating whether
// file storage is available. Called from main.go after storage init.
func SetStorageConfigured(configured bool) {
	storageConfigured = configured
}

// StorageHandler handles file storage admin endpoints.
type StorageHandler struct {
	store storage.ObjectStore
}

// NewStorageHandler creates a StorageHandler.
// store may be nil if storage is not configured.
func NewStorageHandler(store storage.ObjectStore) *StorageHandler {
	return &StorageHandler{store: store}
}

// Configured returns true if a storage backend is available.
func (h *StorageHandler) Configured() bool {
	return h.store != nil
}

// Status returns storage backend status and statistics.
//
//	GET /admin/storage/status
func (h *StorageHandler) Status(c *gin.Context) {
	if h.store == nil {
		c.JSON(http.StatusOK, gin.H{
			"backend":    "none",
			"configured": false,
			"healthy":    false,
		})
		return
	}

	stats, err := h.store.Stats(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":      "failed to collect storage stats",
			"backend":    h.store.Backend(),
			"configured": true,
			"healthy":    false,
		})
		return
	}

	c.JSON(http.StatusOK, stats)
}
