package installer

import (
	"fmt"
	"path/filepath"
)

// DownloadAndExtract downloads a file and extracts it to the target directory
// This is a common pattern used across Windows and macOS installers
func DownloadAndExtract(installer *Installer, cr *CommandRunner, url, targetDir, archiveName string) error {
	if cr != nil {
		if err := installer.EnsureDirWithOutput(cr, targetDir); err != nil {
			return err
		}
	} else {
		if err := installer.EnsureDir(targetDir); err != nil {
			return err
		}
	}

	archivePath := filepath.Join(targetDir, archiveName)

	if cr != nil {
		if err := installer.DownloadFileWithProgressToChannel(cr, url, archivePath); err != nil {
			return fmt.Errorf("download failed: %w", err)
		}
		if err := installer.ExtractArchiveWithOutput(cr, archivePath, targetDir); err != nil {
			return fmt.Errorf("extraction failed: %w", err)
		}
	} else {
		if err := installer.DownloadFile(url, archivePath); err != nil {
			return fmt.Errorf("download failed: %w", err)
		}
		if err := installer.ExtractArchive(archivePath, targetDir); err != nil {
			return fmt.Errorf("extraction failed: %w", err)
		}
	}

	return nil
}
