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

package branches

import (
	stdctx "context"

	gitea "gitea.dev/sdk"

	"gitea.dev/tea/cmd/flags"
	"gitea.dev/tea/modules/context"
	"gitea.dev/tea/modules/print"
	"github.com/urfave/cli/v3"
)

var branchFieldsFlag = flags.FieldsFlag(print.BranchFields, []string{
	"name", "protected", "user-can-merge", "user-can-push",
})

// CmdBranchesListFlags Flags for command list
var CmdBranchesListFlags = append([]cli.Flag{
	branchFieldsFlag,
	&flags.PaginationPageFlag,
	&flags.PaginationLimitFlag,
}, flags.AllDefaultFlags...)

// CmdBranchesList represents a sub command of branches to list branches
var CmdBranchesList = cli.Command{
	Name:        "list",
	Aliases:     []string{"ls"},
	Usage:       "List branches of the repository",
	Description: `List branches of the repository`,
	ArgsUsage:   " ", // command does not accept arguments
	Action:      RunBranchesList,
	Flags:       CmdBranchesListFlags,
}

// RunBranchesList list branches
func RunBranchesList(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
	}

	owner := ctx.Owner
	if ctx.IsSet("owner") {
		owner = ctx.String("owner")
	}

	var branches []*gitea.Branch
	var protections []*gitea.BranchProtection
	branches, _, err = ctx.Login.Client().Repositories.ListRepoBranches(requestCtx, owner, ctx.Repo, gitea.ListRepoBranchesOptions{
		ListOptions: flags.GetListOptions(cmd),
	})
	if err != nil {
		return err
	}

	protections, _, err = ctx.Login.Client().Repositories.ListBranchProtections(requestCtx, owner, ctx.Repo, gitea.ListBranchProtectionsOptions{
		ListOptions: flags.GetListOptions(cmd),
	})
	if err != nil {
		return err
	}

	fields, err := branchFieldsFlag.GetValues(cmd)
	if err != nil {
		return err
	}

	return print.BranchesList(branches, protections, ctx.Output, fields)
}
