/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cli

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
	"go.unistack.org/micro/v4/logger"
)

var updateCmd = NewUpdateCommand()

type UpdateFlags struct {
	all bool
	mod string
}

func init() {
	rootCmd.AddCommand(updateCmd)
}

func NewUpdateCommand() *cobra.Command {
	var flags UpdateFlags

	ctx := context.Background()

	cmd := &cobra.Command{
		Use:   "update",
		Short: "Update allows you to start the process of creating a PR in the repository",
		Long: `
		Update allows you to start the process of creating a PR in the repository. 
		Use the -a flag to update all dependencies or -m flag a specific module.
		`,
		RunE: func(cmd *cobra.Command, args []string) error {
			var err error

			if gitsource == nil {
				return errSourceNil
			}
			if len(mvs) == 0 {
				return errUpdateNotExist
			}

			if flags.all {
				logger.Info(ctx, "update all")
				for pathMod, m := range mvs {
					for _, branch := range cfg.Branches {
						logger.Info(ctx, fmt.Sprintf("update mod: %s", m))

						if err = gitsource.RequestOpen(ctx, branch, pathMod, m); err != nil {
							logger.Error(ctx, fmt.Sprintf("PR open error: %s, base branch: %s", pathMod, branch))
							return err
						}

						logger.Info(ctx, fmt.Sprintf("Successful update mod: %s", pathMod))
					}

					delete(mvs, pathMod) // todo возможно чисть не стоит и нужно просто пропускать
				}
				return nil
			}

			if flags.mod != "" {
				for _, branch := range cfg.Branches {
					logger.Info(ctx, fmt.Sprintf("update mod: %s", flags.mod))

					if _, ok := mvs[flags.mod]; !ok {
						return errUpdateNotExist
					}

					if err = gitsource.RequestOpen(ctx, branch, flags.mod, mvs[flags.mod]); err != nil {
						logger.Error(ctx, fmt.Sprintf("PR open error: %s, base branch: %s", flags.mod, branch))
						return err
					}

					logger.Info(ctx, fmt.Sprintf("Successful update mod: %s", flags.mod))
				}

				delete(mvs, flags.mod)

				return nil
			}

			return errFlagsNotExist
		},
	}

	cmd.Flags().BoolVarP(&flags.all, "all", "a", false, "Updates everything depending")
	cmd.Flags().StringVarP(&flags.mod, "mod", "m", "", "Update one dependency")

	return cmd
}
