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

package organizations

import (
	stdctx "context"
	"fmt"

	"gitea.dev/sdk"

	"gitea.dev/tea/cmd/flags"
	"gitea.dev/tea/modules/context"
	"gitea.dev/tea/modules/print"

	"github.com/urfave/cli/v3"
)

// CmdOrganizationCreate represents a sub command of organizations to delete a given user organization
var CmdOrganizationCreate = cli.Command{
	Name:        "create",
	Aliases:     []string{"c"},
	Usage:       "Create an organization",
	Description: "Create an organization",
	Action:      RunOrganizationCreate,
	ArgsUsage:   "<organization name>",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:    "full-name",
			Aliases: []string{"n"},
		},
		&cli.StringFlag{
			Name:    "description",
			Aliases: []string{"d"},
		},
		&cli.StringFlag{
			Name:    "website",
			Aliases: []string{"w"},
		},
		&cli.StringFlag{
			Name:    "location",
			Aliases: []string{"L"},
		},
		&cli.StringFlag{
			Name:    "visibility",
			Aliases: []string{"v"},
		},
		&cli.BoolFlag{
			Name: "repo-admins-can-change-team-access",
		},
		&flags.LoginFlag,
	},
}

// RunOrganizationCreate sets up a new organization
func RunOrganizationCreate(requestCtx stdctx.Context, cmd *cli.Command) error {
	ctx, err := context.InitCommand(cmd)
	if err != nil {
		return err
	}

	if ctx.Args().Len() < 1 {
		return fmt.Errorf("organization name is required")
	}

	var visibility gitea.VisibleType
	switch ctx.String("visibility") {
	case "", "public":
		visibility = gitea.VisibleTypePublic
	case "private":
		visibility = gitea.VisibleTypePrivate
	case "limited":
		visibility = gitea.VisibleTypeLimited
	default:
		return fmt.Errorf("unknown visibility '%s'", ctx.String("visibility"))
	}

	org, _, err := ctx.Login.Client().Organizations.CreateOrg(requestCtx, gitea.CreateOrgOption{
		Name:                      ctx.Args().First(),
		FullName:                  ctx.String("full-name"),
		Description:               ctx.String("description"),
		Website:                   ctx.String("website"),
		Location:                  ctx.String("location"),
		RepoAdminChangeTeamAccess: ctx.Bool("repo-admins-can-change-team-access"),
		Visibility:                visibility,
	})
	if err != nil {
		return err
	}

	print.OrganizationDetails(org)

	return err
}
