//go:build unix

// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// t_utils_test.go
package expr

import (
	"errors"
	"os/user"
	"path"
	"testing"

	"git.portale-stac.it/go-pkg/expr/util"
)

func TestExpandPathRootOk(t *testing.T) {
	source := "~root"
	wantValue := "/root"

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil || gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, nil)
	}
}

func TestExpandPathRootSubDirOk(t *testing.T) {
	source := "~root/test"
	wantValue := "/root/test"

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil || gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, nil)
	}
}

func TestExpandPathUser(t *testing.T) {
	u, _ := user.Current()
	source := "~"
	wantValue := path.Join("/home", u.Username)

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil || gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, nil)
	}
}

func TestExpandPathEnv(t *testing.T) {
	u, _ := user.Current()
	source := "$HOME"
	wantValue := path.Join("/home", u.Username)

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil || gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, nil)
	}
}

func TestExpandPathErr(t *testing.T) {
	source := "~fake-user/test"
	wantValue := "~fake-user/test"
	wantErr := errors.New(`user: unknown user fake-user`)

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil && gotErr.Error() != wantErr.Error() {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, wantErr)
	} else if gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, wantErr)
	}
}

func TestExpandPathUserErr(t *testing.T) {
	u, _ := user.Current()
	source := "~"
	wantValue := path.Join("/home", u.Username)
	// wantErr := errors.New(`test expected string, got list ([])`)
	wantErr := error(nil)

	gotValue, gotErr := util.ExpandPath(source)

	if gotErr != nil {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, wantErr)
	} else if gotValue != wantValue {
		t.Errorf(`ExpandPath(%v) gotValue=%q, gotErr=%v -> wantValue=%q, wantErr=%v`,
			source, gotValue, gotErr, wantValue, wantErr)
	}
}
