package cmd

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestBackupNonInteractiveMissingPaths(t *testing.T) {
	// Not parallel: mutates package-level isStdinTerminal.

	original := isStdinTerminal
	t.Cleanup(func() {
		isStdinTerminal = original
	})
	isStdinTerminal = func() bool { return false }

	// Config with a valid preset but no backup paths.
	dir := t.TempDir()
	cfg := filepath.Join(dir, "config.toml")
	err := os.WriteFile(cfg, []byte(`
[global]
repo = "/repos/default"

["home@"]
tag = "home"

["@cloud"]
repo = "/repos/cloud"
`), 0o600)
	if err != nil {
		t.Fatalf("writing fixture: %v", err)
	}
	t.Setenv("HOME", dir)

	setRootFlagValuesForTest(t, "home@cloud", true, cfg)
	t.Setenv("KELD_CONFIG_FILE", "")
	t.Setenv("KELD_DRYRUN", "")

	backup := lookupSubcommand(t, "backup")
	_, err = captureStdout(t, func() error {
		return backup.RunE(backup, []string{})
	})

	if err == nil {
		t.Fatal("expected error for backup with no paths, got nil")
	}

	errMsg := err.Error()
	// Should mention paths specifically.
	if !strings.Contains(errMsg, "path") {
		t.Fatalf("expected error to mention paths, got: %v", err)
	}
}

func TestBackupNonInteractiveMultiplePresetsNoSelection(t *testing.T) {
	// Not parallel: mutates package-level isStdinTerminal.

	original := isStdinTerminal
	t.Cleanup(func() {
		isStdinTerminal = original
	})
	isStdinTerminal = func() bool { return false }

	// Config with multiple presets (home@cloud, work@cloud).
	dir := t.TempDir()
	cfg := filepath.Join(dir, "config.toml")
	err := os.WriteFile(cfg, []byte(`
[global]
repo = "/repos/default"

["home@"]
tag = "home"

["home@".backup]
_arguments = "/home"

["work@"]
tag = "work"

["work@".backup]
_arguments = "/work"

["@cloud"]
repo = "/repos/cloud"
`), 0o600)
	if err != nil {
		t.Fatalf("writing fixture: %v", err)
	}
	t.Setenv("HOME", dir)

	// No --preset specified.
	setRootFlagValuesForTest(t, "", true, cfg)
	t.Setenv("KELD_CONFIG_FILE", "")
	t.Setenv("KELD_DRYRUN", "")

	backup := lookupSubcommand(t, "backup")
	_, err = captureStdout(t, func() error {
		return backup.RunE(backup, []string{})
	})

	if err == nil {
		t.Fatal("expected error for multiple presets with no selection, got nil")
	}

	errMsg := err.Error()
	// Should mention multiple presets.
	if !strings.Contains(errMsg, "preset") {
		t.Fatalf("expected error to mention presets, got: %v", err)
	}
}
