package configuration

import (
	"fmt"
	"strings"

	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/lib/git"
	"code.justin.tv/d8a/buddy/lib/store"
	"code.justin.tv/twitch/cli/ghutil"
	"github.com/spf13/cobra"
)

var icemanRepo = &cobra.Command{
	Use:   "iceman-repo [cluster] [github org]/[repo]",
	Short: "Change the iceman migration repository for a cluster",
	Long:  "Change the iceman migration repository for a cluster",
	RunE: func(command *cobra.Command, args []string) error {
		if len(data.ConfigureData.Args()) != 1 {
			return command.Usage()
		}

		repoName := data.ConfigureData.Args()[0]
		repoSeparatorCount := strings.Count(repoName, "/")
		if repoSeparatorCount != 1 {
			return command.Usage()
		}

		repoSeparatorIndex := strings.Index(repoName, "/")
		if repoSeparatorIndex == 0 || repoSeparatorIndex == len(repoName)-1 {
			return command.Usage()
		}

		foundCluster := data.ConfigureData.FoundCluster()
		configFile := data.ConfigureData.ConfigFile()

		if foundCluster.Repository == repoName {
			fmt.Println("No change")
			return nil
		}

		oldRepoName := foundCluster.Repository
		foundCluster.Repository = repoName

		client, err := ghutil.ClientFromToken(configFile.GithubKey)
		if err != nil {
			return err
		}

		err = git.EnsureRepository(configFile, foundCluster, client)
		if err != nil {
			return err
		}

		err = store.UpdateRepository(data.ConfigureData.StoreDB(), foundCluster)
		if err != nil {
			return err
		}

		return git.CleanupRepository(oldRepoName, client)
	},
}

func init() {
	ConfigureCmd.AddCommand(icemanRepo)
}
