package nix_test

import (
	"os"
	"slices"
	"syscall"
	"testing"

	"gensokyo.uk/nix"
	"hakurei.app/command"
)

func init() {
	stubCommandInit = append(stubCommandInit, func(c command.Command) {
		commandStore := c.New(nix.CommandStore, "emit samples for various `nix store` cases")

		var (
			flagSignPBL       bool
			flagSignVerbose   bool
			flagSignRecursive bool
			flagSignKeyFile   string
			flagSignStdin     bool
		)
		commandStore.NewCommand(nix.CommandStoreSign, "emit samples for various `nix store sign` cases", func(args []string) error {
			if !flagSignPBL || !flagSignVerbose || !flagSignRecursive || flagSignKeyFile != nonexistent || !flagSignStdin {
				return syscall.ENOSYS
			}

			installables, err := nix.ReadStdin(os.Stdin)
			if err != nil {
				return err
			}
			if !slices.Equal(installables, instWant["pluiedev pappardelle"]) {
				return syscall.EINVAL
			}
			return nil
		}).
			Flag(&flagSignPBL, trimFlagName(nix.FlagPrintBuildLogs), command.BoolFlag(false), nix.FlagPrintBuildLogs).
			Flag(&flagSignVerbose, trimFlagName(nix.FlagVerbose), command.BoolFlag(false), nix.FlagVerbose).
			Flag(&flagSignRecursive, trimFlagName(nix.FlagRecursive), command.BoolFlag(false), nix.FlagRecursive).
			Flag(&flagSignKeyFile, trimFlagName(nix.FlagKeyFile), command.StringFlag(""), nix.FlagKeyFile).
			Flag(&flagSignStdin, trimFlagName(nix.FlagStdin), command.BoolFlag(false), nix.FlagStdin)
	})
}

func TestSign(t *testing.T) {
	stubNixCommand(t)
	if err := nix.Sign(
		newStubContext(t.Context(), nil, os.Stdout, os.Stderr),
		nonexistent,
		slices.Values(instWant["pluiedev pappardelle"]),
	); err != nil {
		t.Errorf("Sign: error = %v", err)
	}
}
