// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package issues

import (
	"fmt"

	stdctx "context"

	"github.com/urfave/cli/v3"

	"gitea.dev/tea/cmd/flags"
	"gitea.dev/tea/modules/context"
	"gitea.dev/tea/modules/interact"
	"gitea.dev/tea/modules/print"
	"gitea.dev/tea/modules/task"
	"gitea.dev/tea/modules/utils"
)

// CmdIssuesEdit is the subcommand of issues to edit issues
var CmdIssuesEdit = cli.Command{
	Name:    "edit",
	Aliases: []string{"e"},
	Usage:   "Edit one or more issues",
	Description: `Edit one or more issues. To unset a property again,
use an empty string (eg. --milestone "").`,
	ArgsUsage: "<idx> [<idx>...]",
	Action:    runIssuesEdit,
	Flags:     flags.IssuePREditFlags,
}

func runIssuesEdit(requestCtx stdctx.Context, cmd *cli.Command) error {
	ctx, err := context.InitCommand(cmd)
	if err != nil {
		return err
	}
	if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
		return err
	}

	if !cmd.Args().Present() {
		return fmt.Errorf("must specify at least one issue index")
	}

	opts, err := flags.GetIssuePREditFlags(ctx)
	if err != nil {
		return err
	}

	indices, err := utils.ArgsToIndices(ctx.Args().Slice())
	if err != nil {
		return err
	}

	client := ctx.Login.Client()
	for _, opts.Index = range indices {
		if ctx.IsInteractiveMode() {
			var err error
			opts, err = interact.EditIssue(requestCtx, *ctx, opts.Index)
			if err != nil {
				if interact.IsQuitting(err) {
					return nil // user quit
				}
				return err
			}
		}

		issue, err := task.EditIssue(requestCtx, ctx, client, *opts)
		if err != nil {
			return err
		}
		if ctx.Args().Len() > 1 {
			fmt.Println(issue.HTMLURL)
		} else {
			print.IssueDetails(issue, nil)
		}
	}

	return nil
}
