package handlers

import (
	"os"
	"strconv"
	"strings"
	"time"

	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/objet"
)

// parseDateTime parse une date ISO-8601.
func parseDateTime(value string) (time.Time, error) {
	return time.Parse(time.RFC3339, value)
}

// resolveCategorie determine la categorie d'une piece jointe.
func resolveCategorie(ext string, mime string) string {
	ext = strings.ToLower(ext)
	mime = strings.ToLower(mime)
	if ext == ".md" || mime == "text/markdown" {
		return "markdown_tuto"
	}
	if mime == "application/pdf" || ext == ".pdf" {
		return "pdf_notice"
	}
	if strings.HasPrefix(mime, "image/") {
		return "image"
	}
	return "image"
}

// maxUploadBytes retourne la taille max d'un fichier en octets.
func maxUploadBytes() int64 {
	const defaultMB = 50
	value := os.Getenv("MAX_UPLOAD_MB")
	if value == "" {
		return defaultMB * 1024 * 1024
	}
	parsed, err := strconv.Atoi(value)
	if err != nil || parsed <= 0 {
		return defaultMB * 1024 * 1024
	}
	return int64(parsed) * 1024 * 1024
}

// parsePagination calcule la limite et l'offset a partir des params page/limit.
func parsePagination(pageValue string, limitValue string) (int, int, int) {
	const (
		defaultLimit = 50
		maxLimit     = 200
	)

	page := 1
	if pageValue != "" {
		if parsed, err := strconv.Atoi(pageValue); err == nil && parsed > 0 {
			page = parsed
		}
	}

	limit := defaultLimit
	if limitValue != "" {
		if parsed, err := strconv.Atoi(limitValue); err == nil && parsed > 0 {
			limit = parsed
		}
	}
	if limit > maxLimit {
		limit = maxLimit
	}

	offset := (page - 1) * limit
	return limit, offset, page
}

// isAllowedUpload valide le type de fichier (images, PDF, Markdown).
func isAllowedUpload(mime string, ext string) bool {
	mime = strings.ToLower(mime)
	ext = strings.ToLower(ext)
	if strings.HasPrefix(mime, "image/") {
		return true
	}
	if mime == "application/pdf" || ext == ".pdf" {
		return true
	}
	if mime == "text/markdown" || ext == ".md" || ext == ".markdown" {
		return true
	}
	if mime == "text/plain" && (ext == ".md" || ext == ".markdown") {
		return true
	}
	return false
}

// parseStatut convertit un statut texte vers l'enum Ent.
func parseStatut(value string) (objet.Statut, bool) {
	switch value {
	case "en_stock":
		return objet.StatutEnStock, true
	case "pret":
		return objet.StatutPret, true
	case "hors_service":
		return objet.StatutHorsService, true
	case "archive":
		return objet.StatutArchive, true
	default:
		return "", false
	}
}
