package controller

import (
	"context"
	"fmt"
	"log"
	"strings"
	"sync"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/storage/db"

	"github.com/jackc/pgx/v5/pgtype"
)

// FullProjectInit
/*
	Deprecated method to create a project with all related data:
	- git;
	- git for the project's build;
	- cloud folder;
*/
func (wc *WorkflowController) FullProjectInit(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).Folder
	}(&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
	}
	ctx := context.TODO()

	insertedTicket, err := wc.q.CreateTicket(ctx, db.CreateTicketParams{
		Key:       pgtype.Text{String: appKey, Valid: true},
		Channelid: pgtype.Text{},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Print(insertedTicket)

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

	return appKey, nil
}
