package clisetup

import (
	"fmt"
	"io"

	"github.com/spf13/cobra"

	"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/args"
	"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/clisetup/setup"
)

func (cli *cliSetup) newValidateCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "validate [setup_file]",
		Short: "Validate a setup file",
		Long: `Validate a setup file generated by 'cscli setup detect' or manually edited.

This command checks the fields of the setup file, and validates
each acquisition configuration according to its datasource type.

It is especially useful if you have edited the file manually or
generated it through other means.`,
		Example: `cscli setup validate setup.yaml`,

		Args:              args.ExactArgs(1),
		DisableAutoGenTag: true,
		RunE: func(cmd *cobra.Command, args []string) error {
			inputReader, err := maybeStdinFile(args[0])
			if err != nil {
				return err
			}

			return cli.validate(inputReader)
		},
	}

	return cmd
}

func (cli *cliSetup) validate(input io.Reader) error {
	if _, err := setup.ParseSetupYAML(input, true, cli.cfg().Cscli.Color != "no"); err != nil {
		return fmt.Errorf("invalid setup file: %w", err)
	}

	return nil
}
