package release

import (
	"fmt"
	"net/url"

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

func Shortcuts() []*common.Shortcut {
	return []*common.Shortcut{
		{
			Name:        "list",
			Description: "List releases",
			Flags: []common.Flag{
				{Name: "page", Short: "p", Usage: "Page number", Default: "1"},
				{Name: "limit", Short: "l", Usage: "Items per page", Default: "20"},
			},
			Run: func(ctx *common.RuntimeContext) error {
				if err := ctx.ResolveOwnerRepo(); err != nil {
					return err
				}
				q := url.Values{}
				q.Set("page", ctx.Arg("page"))
				q.Set("limit", ctx.Arg("limit"))
				env, err := ctx.CallAPIWithQuery("GET", ctx.RepoPath()+"/releases", q)
				if err != nil {
					return fmt.Errorf("获取 Release 列表失败: %w", err)
				}
				return ctx.Output(env)
			},
		},
		{
			Name:        "create",
			Description: "Create a release",
			DryRun:      true,
			DryRunHint: func(ctx *common.RuntimeContext) (string, error) {
				name := ctx.Arg("name")
				tag := ctx.Arg("tag")
				return fmt.Sprintf("Create release: %s (tag: %s)", name, tag), nil
			},
			Flags: []common.Flag{
				{Name: "tag", Short: "t", Usage: "Tag name", Required: true},
				{Name: "name", Short: "n", Usage: "Release name", Required: true},
				{Name: "body", Short: "b", Usage: "Release notes"},
				{Name: "target", Usage: "Target branch", Default: "master"},
				{Name: "prerelease", Usage: "Mark as prerelease (true/false)", Default: "false"},
			},
			Run: func(ctx *common.RuntimeContext) error {
				if err := ctx.ResolveOwnerRepo(); err != nil {
					return err
				}
				tag, err := ctx.RequireArg("tag", "--tag v1.0.0")
				if err != nil {
					return err
				}
				name, err := ctx.RequireArg("name", `--name "Version 1.0.0"`)
				if err != nil {
					return err
				}
				payload := map[string]interface{}{
					"tag_name": tag,
					"name":     name,
				}
				if b := ctx.Arg("body"); b != "" {
					payload["body"] = b
				}
				if t := ctx.Arg("target"); t != "" {
					payload["target_commitish"] = t
				}
				if ctx.Arg("prerelease") == "true" {
					payload["prerelease"] = true
				}
				env, err := ctx.CallAPI("POST", ctx.RepoPath()+"/releases", payload)
				if err != nil {
					return fmt.Errorf("创建 Release 失败: %w", err)
				}
				return ctx.Output(env)
			},
		},
		{
			Name:        "view",
			Description: "View release details",
			Flags: []common.Flag{
				{Name: "id", Short: "i", Usage: "Release ID or tag", Required: true},
			},
			Run: func(ctx *common.RuntimeContext) error {
				if err := ctx.ResolveOwnerRepo(); err != nil {
					return err
				}
				id, err := ctx.RequireArg("id", "--id 1")
				if err != nil {
					return err
				}
				env, err := ctx.CallAPI("GET", fmt.Sprintf("%s/releases/%s", ctx.RepoPath(), id), nil)
				if err != nil {
					return fmt.Errorf("查看 Release 失败: %w", err)
				}
				return ctx.Output(env)
			},
		},
		{
			Name:        "delete",
			Description: "Delete a release",
			DryRun:      true,
			DryRunHint: func(ctx *common.RuntimeContext) (string, error) {
				id := ctx.Arg("id")
				return fmt.Sprintf("Delete release #%s", id), nil
			},
			Flags: []common.Flag{
				{Name: "id", Short: "i", Usage: "Release ID", Required: true},
			},
			Run: func(ctx *common.RuntimeContext) error {
				if err := ctx.ResolveOwnerRepo(); err != nil {
					return err
				}
				id, err := ctx.RequireArg("id", "--id 1")
				if err != nil {
					return err
				}
				_, delErr := ctx.CallAPI("DELETE", fmt.Sprintf("%s/releases/%s", ctx.RepoPath(), id), nil)
				if delErr != nil {
					_, viewErr := ctx.CallAPI("GET", fmt.Sprintf("%s/releases/%s", ctx.RepoPath(), id), nil)
					if viewErr != nil {
						return ctx.Output(output.SuccessEnvelope(map[string]interface{}{
							"message": "删除成功",
						}, nil))
					}
					return fmt.Errorf("删除 Release 失败: %w", delErr)
				}
				return ctx.Output(output.SuccessEnvelope(map[string]interface{}{
					"message": "删除成功",
				}, nil))
			},
		},
		{
			Name:        "update",
			Description: "Update a release",
			Flags: []common.Flag{
				{Name: "id", Short: "i", Usage: "Release ID", Required: true},
				{Name: "name", Short: "n", Usage: "New release name"},
				{Name: "body", Short: "b", Usage: "New release notes"},
				{Name: "prerelease", Usage: "Mark as prerelease (true/false)"},
			},
			Run: func(ctx *common.RuntimeContext) error {
				if err := ctx.ResolveOwnerRepo(); err != nil {
					return err
				}
				id, _ := ctx.RequireArg("id", "--id my-org")
				body := map[string]interface{}{}
				if n := ctx.Arg("name"); n != "" {
					body["name"] = n
				}
				if b := ctx.Arg("body"); b != "" {
					body["body"] = b
				}
				if p := ctx.Arg("prerelease"); p != "" {
					body["prerelease"] = p == "true"
				}
				if len(body) == 0 {
					return fmt.Errorf("at least one of --name, --body, --prerelease is required")
				}
				env, err := ctx.CallAPI("PATCH", fmt.Sprintf("%s/releases/%s", ctx.RepoPath(), id), body)
				if err != nil {
					return err
				}
				return ctx.Output(env)
			},
		},
	}
}
