package e2e_test

import (
	"encoding/json"
	"slices"
	"strings"
	"testing"
)

func TestAliases(t *testing.T) {
	env := newTestEnv(t, "testuser")

	t.Run("DefaultsPresent", func(t *testing.T) {
		out := env.mustAx("alias", "--json")
		var aliases []map[string]string
		if err := json.Unmarshal([]byte(out), &aliases); err != nil {
			t.Fatalf("failed to parse alias JSON: %v\n%s", err, out)
		}
		names := make([]string, len(aliases))
		for i, a := range aliases {
			names[i] = a["name"]
		}
		for _, want := range []string{"mine", "due", "inbox"} {
			if !slices.Contains(names, want) {
				t.Errorf("default alias %q not found in: %v", want, names)
			}
		}
	})

	t.Run("Create_Show_Delete", func(t *testing.T) {
		env.mustAx("alias", "myopen", "list --status open", "--desc", "My open issues")

		showOut, err := env.ax("alias", "myopen")
		if err != nil {
			t.Fatalf("alias show failed: %v\n%s", err, showOut)
		}
		if !strings.Contains(showOut, "list --status open") {
			t.Errorf("alias command not found in show output: %s", showOut)
		}

		env.mustAx("alias", "del", "myopen")

		_, err = env.ax("alias", "myopen")
		if err == nil {
			t.Fatal("expected error after alias deletion, got none")
		}
	})

	t.Run("CannotDeleteDefault", func(t *testing.T) {
		_, err := env.ax("alias", "del", "inbox")
		if err == nil {
			t.Fatal("expected error deleting default alias, got none")
		}
	})

	t.Run("Execute_Due", func(t *testing.T) {
		// The built-in 'due' alias lists open issues.
		out := env.mustAx("due", "--json")
		env.parseNodes(out)
	})

	t.Run("Execute_Mine_WithMeExpansion", func(t *testing.T) {
		// 'mine' expands $me to AX_USER=testuser.
		out := env.mustAx("mine", "--json")
		env.parseNodes(out)
	})
}
