package controllers

import (
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"github.com/gin-gonic/gin"
)

func getDirectorySize(path string) (int64, error) {
	var size int64
	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			size += info.Size()
		}
		return err
	})
	return size, err
}

func HandleStorageInfo(c *gin.Context) {
	uploadDir := os.Getenv("UPLOAD_DIR")
	if uploadDir == "" {
		uploadDir = "./uploads"
	}

	maxStorageEnv := os.Getenv("MAX_STORAGE_GB")
	if maxStorageEnv == "" {
		maxStorageEnv = "10"
	}

	maxStorageGB, err := strconv.ParseFloat(maxStorageEnv, 64)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid MAX_STORAGE_GB configuration"})
		return
	}

	if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
		if err := os.MkdirAll(uploadDir, 0755); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create upload directory"})
			return
		}
	}

	usedBytes, err := getDirectorySize(uploadDir)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to calculate storage usage"})
		return
	}

	maxBytes := int64(maxStorageGB * 1024 * 1024 * 1024)
	usedGB := float64(usedBytes) / (1024 * 1024 * 1024)
	usagePercent := (float64(usedBytes) / float64(maxBytes)) * 100

	c.JSON(http.StatusOK, gin.H{
		"storage": gin.H{
			"used_bytes":     usedBytes,
			"used_gb":        usedGB,
			"max_gb":         maxStorageGB,
			"max_bytes":      maxBytes,
			"usage_percent":  usagePercent,
			"available_gb":   maxStorageGB - usedGB,
			"available_bytes": maxBytes - usedBytes,
		},
	})
}