package nix_test

import (
	"errors"
	"slices"
	"strings"
	"syscall"
	"testing"

	"gensokyo.uk/nix"
)

func TestStdin(t *testing.T) {
	testCases := []struct {
		name string
		col  []string
		raw  string
	}{
		{"getchoo atlas", getchooAtlasCollective, getchooAtlasStdin},
		{"getchoo glados", getchooGladosCollective, getchooGladosStdin},
		{"pluiedev pappardelle", pluiedevPappardelleCollective, pluiedevPappardelleStdin},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			t.Run("write", func(t *testing.T) {
				w := new(strings.Builder)

				if _, err := nix.WriteStdin(w, slices.Values(tc.col)); err != nil {
					t.Fatalf("cannot write: %v", err)
				}
				if w.String() != tc.raw {
					t.Errorf("WriteStdin:\n%s\nwant:\n%s", w.String(), tc.raw)
				}
			})

			t.Run("read", func(t *testing.T) {
				r := strings.NewReader(tc.raw)
				got, err := nix.ReadStdin(r)
				if err != nil {
					t.Fatalf("cannot read: %v", err)
				}
				if !slices.Equal(got, tc.col) {
					t.Errorf("ReadStdin: %#v, want %#v", got, tc.col)
				}
			})
		})
	}

	t.Run("write error", func(t *testing.T) {
		n, err := nix.WriteStdin(errorWriter{}, slices.Values([]string{"/nix/store"}))
		if n != 0 {
			panic("unreachable")
		}
		if !errors.Is(err, syscall.EIO) {
			t.Errorf("WriteStdin: error = %v, want %v", err, syscall.EIO)
		}
	})
}

func TestInstallable(t *testing.T) {
	testCases := []struct {
		name, flake, host, want string
	}{
		{"satori", "/var/lib/persist/nixos", "satori", "/var/lib/persist/nixos#nixosConfigurations.satori.config.system.build.toplevel"},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			got := nix.InstallableNixOS(tc.flake, tc.host)
			if got != tc.want {
				t.Errorf("Installable(%q, %q): %q, want %q",
					tc.flake, tc.host, got, tc.want)
			}
		})
	}
}
