package java

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/anchore/syft/internal/tmpdir"
)

func saveArchiveToTmp(td *tmpdir.TempDir, archiveVirtualPath string, reader io.Reader) (string, string, func(), error) {
	name := filepath.Base(archiveVirtualPath)
	tempDir, cleanupFn, err := td.NewChild("archive-contents") //nolint:gocritic // cleanup is returned to caller, not deferred here
	if err != nil {
		return "", "", func() {}, fmt.Errorf("unable to create tempdir for archive processing: %w", err)
	}

	archivePath := filepath.Join(tempDir, "archive-"+name)
	contentDir := filepath.Join(tempDir, "contents")

	err = os.Mkdir(contentDir, 0755)
	if err != nil {
		return contentDir, "", cleanupFn, fmt.Errorf("unable to create processing tempdir: %w", err)
	}

	archiveFile, err := os.Create(archivePath)
	if err != nil {
		return contentDir, "", cleanupFn, fmt.Errorf("unable to create archive: %w", err)
	}
	defer archiveFile.Close()

	// note: no size limit here — the reader comes from a file already enumerated by the
	// resolver, not from an untrusted network source. The file size is bounded by the
	// source image/directory being scanned.
	_, err = io.Copy(archiveFile, reader)
	if err != nil {
		return contentDir, archivePath, cleanupFn, fmt.Errorf("unable to copy archive: %w", err)
	}

	return contentDir, archivePath, cleanupFn, nil
}
