package updates

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"
)

type HTTPDownloader struct {
	client *http.Client
}

func NewHTTPDownloader(client *http.Client) *HTTPDownloader {
	if client == nil {
		client = http.DefaultClient
	}
	return &HTTPDownloader{client: client}
}

func (downloader *HTTPDownloader) Download(ctx context.Context, artifact Artifact) (DownloadedFile, error) {
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, artifact.URL, nil)
	if err != nil {
		return DownloadedFile{}, err
	}

	response, err := downloader.client.Do(request)
	if err != nil {
		return DownloadedFile{}, err
	}
	defer response.Body.Close()

	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return DownloadedFile{}, fmt.Errorf("unexpected download status: %s", response.Status)
	}

	file, err := os.CreateTemp("", "wails3kit-download-*")
	if err != nil {
		return DownloadedFile{}, err
	}
	defer file.Close()

	hash := sha256.New()
	written, err := io.Copy(io.MultiWriter(file, hash), response.Body)
	if err != nil {
		_ = os.Remove(file.Name())
		return DownloadedFile{}, err
	}

	return DownloadedFile{
		Path:   file.Name(),
		Size:   written,
		SHA256: hex.EncodeToString(hash.Sum(nil)),
	}, nil
}
