package util_test

import (
	"galaxy/util"
	"os"
	"path/filepath"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
)

func TestPathExists(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	testDirExistsFunc(t, root, func(s string) (bool, error) { return util.PathExists(s, true) })
	testFileExistsFunc(t, root, func(s string) (bool, error) { return util.PathExists(s, false) })
}

func TestDirExists(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	testDirExistsFunc(t, root, util.DirExists)
}

func TestFileExists(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	testFileExistsFunc(t, root, util.FileExists)
}

func testDirExistsFunc(t *testing.T, root string, dirCheck func(string) (bool, error)) {
	exists, err := dirCheck(root)
	assert.NoError(t, err, "directory existence check")
	assert.True(t, exists, "directory should exist")
	nonExistentDir := filepath.Join(root, uuid.New().String())
	exists, err = dirCheck(nonExistentDir)
	assert.NoError(t, err, "non-existent directory existence check")
	assert.False(t, exists, "non-existent directory should not exist")
}

func testFileExistsFunc(t *testing.T, root string, fileCheck func(string) (bool, error)) {
	fpath := createTempFile(t, root)
	exists, err := fileCheck(fpath)
	assert.NoError(t, err, "file existence check")
	assert.True(t, exists, "file should exist")
	nonExistentFile := filepath.Join(root, uuid.New().String())
	exists, err = fileCheck(nonExistentFile)
	assert.NoError(t, err, "non-existent file existence check")
	assert.False(t, exists, "non-existent file should not exist")
}

func createTempFile(t *testing.T, root string) string {
	t.Helper()

	fd, err := os.CreateTemp(root, "a-file")
	if err != nil {
		assert.FailNow(t, "create temporary file", err)
		return ""
	}
	if err := fd.Close(); err != nil {
		assert.FailNow(t, "close temporary file", err)
		return ""
	}
	return fd.Name()
}
