package controller

import (
	"fmt"
	"strings"
	"sync"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/services"
)

type WorkflowController struct {
	iGit   services.IGit
	iCloud services.ICloud
	iCoda  services.ICoda
}

func NewWorkflowController(
	git services.IGit,
	cloud services.ICloud,
	coda services.ICoda,
) *WorkflowController {
	return &WorkflowController{
		iGit:   git,
		iCloud: cloud,

		iCoda: coda,
	}
}

type IWorkflowController interface {
	Workflow(name, key, id string) (string, error)
}

func (wc *WorkflowController) Workflow(name, key, id string) (string, error) {

	appKey := fmt.Sprintf("%s-%s", key, id)

	var (
		git, gitBuild *domain.Git
		cloud         *domain.Folder
	)

	var wg sync.WaitGroup
	wg.Add(3)

	go func(ref **domain.Git) {
		defer wg.Done()
		*ref, _ = wc.iGit.CreateRepo(appKey)
	}(&git)

	go func(ref **domain.Git) {
		defer wg.Done()
		*ref, _ = wc.iGit.CreateRepo(appKey + "-build")
	}(&gitBuild)

	go func(ref **domain.Folder) {
		defer wg.Done()
		*ref, _ = wc.iCloud.CreateFolder(appKey)
	}(&cloud)

	wg.Wait()

	var gitResult, gitBuildResult, cloudResult string

	if git == nil {
		gitResult = "cannot create git"
	} else {
		gitResult = git.HtmlUrl
	}

	if gitBuild == nil {
		gitBuildResult = "cannot create git"
	} else {
		gitBuildResult = fmt.Sprintf("ssh://%s/%s.git", gitBuild.SshUrl, gitBuild.FullName)
	}

	if cloud == nil {
		cloudResult = "cannot create folder"
	} else {
		cloudResult = cloud.PrivateURL
	}

	wc.iCoda.CreateApp(domain.CodaApplication{
		ID:       appKey,
		Summary:  strings.TrimSpace(name),
		Git:      gitResult,
		GitBuild: gitBuildResult,
		Folder:   cloudResult,
	})

	return appKey, nil
}
