package approvers

import (
	"fmt"

	"github.com/spf13/cobra"

	"gitlab.com/gitlab-org/cli/internal/cmdutils"
	"gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
	"gitlab.com/gitlab-org/cli/internal/mcpannotations"
)

func NewCmdApprovers(f cmdutils.Factory) *cobra.Command {
	mrApproversCmd := &cobra.Command{
		Use:     "approvers [<id> | <branch>] [flags]",
		Short:   `List eligible approvers for merge requests in any state.`,
		Long:    ``,
		Aliases: []string{},
		Args:    cobra.MaximumNArgs(1),
		Annotations: map[string]string{
			mcpannotations.Safe: "true",
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			client, err := f.GitLabClient()
			if err != nil {
				return err
			}

			// Obtain the MR from the positional arguments, but allow users to find approvers for
			// merge requests in any valid state
			mr, repo, err := mrutils.MRFromArgs(f, args, "any")
			if err != nil {
				return err
			}

			fmt.Fprintf(f.IO().StdOut, "\nListing merge request !%d eligible approvers:\n", mr.IID)

			mrApprovals, _, err := client.MergeRequestApprovals.GetApprovalState(repo.FullName(), mr.IID)
			if err != nil {
				return err
			}

			mrutils.PrintMRApprovalState(f.IO(), mrApprovals)

			return nil
		},
	}

	return mrApproversCmd
}
