package recipe

import (
	"context"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/go-git/go-git/v5"
	"github.com/urfave/cli/v3"
)

var recipeResetCommand = cli.Command{
	Name:          "reset",
	Usage:         "Remove all unstaged changes from recipe config",
	Description:   "WARNING: this will delete your changes. Be Careful.",
	Aliases:       []string{"rs"},
	UsageText:     "abra recipe reset <recipe> [options]",
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.RecipeNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		recipeName := cmd.Args().First()
		r := recipe.Get(recipeName)

		if recipeName != "" {
			internal.ValidateRecipe(cmd)
		}

		repo, err := git.PlainOpen(r.Dir)
		if err != nil {
			log.Fatal(err)
		}

		ref, err := repo.Head()
		if err != nil {
			log.Fatal(err)
		}

		worktree, err := repo.Worktree()
		if err != nil {
			log.Fatal(err)
		}

		opts := &git.ResetOptions{Commit: ref.Hash(), Mode: git.HardReset}
		if err := worktree.Reset(opts); err != nil {
			log.Fatal(err)
		}

		return nil
	},
}
