package handlers

import (
	"os"

	"git.elijahkuntz.com/Elijah/drive/config"
	"git.elijahkuntz.com/Elijah/drive/database"
	"github.com/gofiber/fiber/v2"
)

type HealthHandler struct {
	DB     *database.DB
	Config *config.Config
}

// Health returns the application health status including DB and storage availability.
// GET /health
func (h *HealthHandler) Health(c *fiber.Ctx) error {
	status := "healthy"
	dbOk := true
	storageOk := true

	// Check database
	if err := h.DB.Ping(); err != nil {
		dbOk = false
		status = "degraded"
	}

	// Check storage directory
	if _, err := os.Stat(h.Config.StorageDir); os.IsNotExist(err) {
		storageOk = false
		status = "degraded"
	}

	// Check data directory
	dataOk := true
	if _, err := os.Stat(h.Config.DataDir); os.IsNotExist(err) {
		dataOk = false
		status = "degraded"
	}

	statusCode := fiber.StatusOK
	if status != "healthy" {
		statusCode = fiber.StatusServiceUnavailable
	}

	return c.Status(statusCode).JSON(fiber.Map{
		"status":  status,
		"db":      dbOk,
		"storage": storageOk,
		"data":    dataOk,
	})
}
