package pr

import (
	"fmt"

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

func newApproveShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "approve",
		Description: "Approve a pull request",
		Flags: []common.Flag{
			{Name: "id", Short: "i", Usage: "PR number", Required: true},
			{Name: "body", Short: "b", Usage: "Review comment (optional)"},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			id, _ := ctx.RequireArg("id", "--id 42")
			body := map[string]interface{}{
				"state": "approved",
			}
			if b := ctx.Arg("body"); b != "" {
				body["body"] = b
			}
			env, err := ctx.CallAPI("POST", fmt.Sprintf("%s/pulls/%s/reviews", ctx.RepoPath(), id), body)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}

func newRequestChangesShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "request-changes",
		Description: "Request changes on a pull request",
		Flags: []common.Flag{
			{Name: "id", Short: "i", Usage: "PR number", Required: true},
			{Name: "body", Short: "b", Usage: "Review comment explaining what needs to change", Required: true},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			id, _ := ctx.RequireArg("id", "--id 42")
			body, _ := ctx.RequireArg("body", `--body "Looks good"`)
			payload := map[string]interface{}{
				"state": "changes_requested",
				"body":  body,
			}
			env, err := ctx.CallAPI("POST", fmt.Sprintf("%s/pulls/%s/reviews", ctx.RepoPath(), id), payload)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}

func newReviewsShortcut() *common.Shortcut {
	return &common.Shortcut{
		Name:        "reviews",
		Description: "List reviews for a pull request",
		Flags: []common.Flag{
			{Name: "id", Short: "i", Usage: "PR number", Required: true},
		},
		Run: func(ctx *common.RuntimeContext) error {
			if err := ctx.ResolveOwnerRepo(); err != nil {
				return err
			}
			id, _ := ctx.RequireArg("id", "--id 42")
			env, err := ctx.CallAPI("GET", fmt.Sprintf("%s/pulls/%s/reviews", ctx.RepoPath(), id), nil)
			if err != nil {
				return err
			}
			return ctx.Output(env)
		},
	}
}
