// monorepo/cloud/backend/internal/maplefile/repo/fileobjectstorage/presigned_download_url.go
package fileobjectstorage

import (
	"context"
	"net/url"
	"time"

	"go.uber.org/zap"
)

// GeneratePresignedDownloadURL creates a time-limited URL that allows direct download
// of the file data located at the given storage path, with proper content disposition headers.
func (impl *fileObjectStorageRepositoryImpl) GeneratePresignedDownloadURL(storagePath string, duration time.Duration) (string, error) {
	ctx := context.Background()

	// Generate presigned download URL with content disposition
	presignedURL, err := impl.Storage.GetDownloadablePresignedURL(ctx, storagePath, duration)
	if err != nil {
		impl.Logger.Error("Failed to generate presigned download URL",
			zap.String("storagePath", storagePath),
			zap.Duration("duration", duration),
			zap.Error(err))
		return "", err
	}

	// Replace the hostname in the presigned URL with the public endpoint if configured
	if impl.Config.S3.PublicEndpoint != "" && impl.Config.S3.PublicEndpoint != impl.Config.S3.Endpoint {
		parsedURL, err := url.Parse(presignedURL)
		if err == nil {
			// Parse the public endpoint to get the host
			publicEndpoint, err := url.Parse(impl.Config.S3.PublicEndpoint)
			if err == nil {
				// Replace the host in the presigned URL
				parsedURL.Scheme = publicEndpoint.Scheme
				parsedURL.Host = publicEndpoint.Host
				presignedURL = parsedURL.String()

				impl.Logger.Debug("Replaced presigned URL hostname with public endpoint",
					zap.String("original_endpoint", impl.Config.S3.Endpoint),
					zap.String("public_endpoint", impl.Config.S3.PublicEndpoint))
			}
		}
	}

	impl.Logger.Debug("Generated presigned download URL",
		zap.String("storagePath", storagePath),
		zap.Duration("duration", duration),
		zap.String("url", presignedURL))

	return presignedURL, nil
}
