// Package utils provides helper functions for URL resolution, ISBN handling, and tag management.
package utils

import (
	"fmt"
	"net/url"
	"path/filepath"
	"strings"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgtype"
)

// ResolveMediaURL resolves a relative path (cover or file) to a full URL
func ResolveMediaURL(libraryID pgtype.UUID, relativePath pgtype.Text) string {
	if !relativePath.Valid || relativePath.String == "" {
		return ""
	}

	if strings.HasPrefix(relativePath.String, "/uploads/") {
		return relativePath.String
	}

	if filepath.IsAbs(relativePath.String) {
		return relativePath.String
	}

	libraryIDStr := uuid.UUID(libraryID.Bytes).String()
	segments := strings.Split(relativePath.String, "/")
	for i, seg := range segments {
		segments[i] = url.PathEscape(seg)
	}
	encodedPath := strings.Join(segments, "/")
	return fmt.Sprintf("/uploads/library-%s/%s", libraryIDStr, encodedPath)
}
