package helpers

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func GenerateProfileImagePath(userID uint, originalFileName string) (string, string, error) {

	uploadDir := "uploads/users/profile"

	if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
		err = os.MkdirAll(uploadDir, 0755)
		if err != nil {
			return "", "", err
		}
	}

	extension := strings.ToLower(filepath.Ext(originalFileName))

	fileName := fmt.Sprintf(
		"user_%d_%d%s",
		userID,
		time.Now().Unix(),
		extension,
	)

	savePath := filepath.Join(uploadDir, fileName)

	return savePath, fileName, nil
}

// LocalPathFromPublicURL maps a stored public image URL
// (https://host/uploads/users/profile/x.jpg) back to its on-disk path
// (uploads/users/profile/x.jpg), so the file can be deleted.
// Returns "" when the stored value is not an uploads path.
func LocalPathFromPublicURL(imageURL string) string {

	normalized := strings.ReplaceAll(imageURL, "\\", "/")

	index := strings.Index(normalized, "uploads/")

	if index == -1 {
		return ""
	}

	relative := normalized[index:]

	// Never act on a traversal path coming out of the database.
	if strings.Contains(relative, "..") {
		return ""
	}

	return filepath.FromSlash(relative)
}
