package issue

import (
	"fmt"

	"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)

func newLabelAddShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "label-add",
		Description: "Add labels to an issue",
		Flags: []common.Flag{
			{Name: "number", Short: "n", Usage: "Issue number", Required: true},
			{Name: "labels", Short: "l", Usage: "Comma-separated label names or IDs", Required: true},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			number, _ := ctx.RequireArg("number", "--number 42")
			labelsStr, _ := ctx.RequireArg("labels", `--labels "bug,urgent"`)
			body := map[string]interface{}{
				"labels": labelsStr,
			}
			env, err := ctx.CallAPI("POST", fmt.Sprintf("%s/issues/%s/labels", v1RepoPath(ctx), number), body)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}

func newLabelRemoveShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "label-remove",
		Description: "Remove a label from an issue",
		Flags: []common.Flag{
			{Name: "number", Short: "n", Usage: "Issue number", Required: true},
			{Name: "label", Short: "l", Usage: "Label ID to remove", Required: true},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			number, _ := ctx.RequireArg("number", "--number 42")
			label, _ := ctx.RequireArg("label", "--label bug")
			env, err := ctx.CallAPI("DELETE", fmt.Sprintf("%s/issues/%s/labels/%s", v1RepoPath(ctx), number, label), nil)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}

func newLabelListShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "label-list",
		Description: "List labels on an issue",
		Flags: []common.Flag{
			{Name: "number", Short: "n", Usage: "Issue number", Required: true},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			number, _ := ctx.RequireArg("number", "--number 42")
			env, err := ctx.CallAPI("GET", fmt.Sprintf("%s/issues/%s/labels", v1RepoPath(ctx), number), nil)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}
