package main

import (
	"bufio"
	"fmt"
	"log"
	"path"
	"strings"

	"src.opensuse.org/autogits/common"
)

func prGitBranchNameForPR(req *common.PullRequestWebhookEvent) string {
	return fmt.Sprintf("PR_%s#%d", req.Repository.Name, req.Pull_Request.Number)
}

func updateSubmoduleInPR(req *common.PullRequestWebhookEvent, git common.Git) {
	common.PanicOnError(git.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--checkout", "--depth", "1", req.Repository.Name))
	common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, req.Repository.Name), "fetch", "--depth", "1", "origin", req.Pull_Request.Head.Sha))
	common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, req.Repository.Name), "checkout", req.Pull_Request.Head.Sha))
}

func processPrjGitPullRequestSync(req *common.PullRequestWebhookEvent) error {
	//	req := h.Data.(*common.PullRequestAction)

	return nil
}

type PullRequestSynced struct {
	gitea common.Gitea
}

func (o *PullRequestSynced) Process(req *common.PullRequestWebhookEvent, git common.Git, config *common.AutogitConfig) error {
	if req.Repository.Name == config.GitProjectName {
		return processPrjGitPullRequestSync(req)
	}

	// need to verify that submodule in the PR for prjgit
	// is still pointing to the HEAD of the PR
	pr, err := o.gitea.GetPullRequest(req.Repository.Owner.Username, req.Repository.Name, req.Number)
	if err != nil {
		return fmt.Errorf("Cannot fetch PR data from gitea: %w", err)
	}

	_, prs := common.ExtractDescriptionAndPRs(bufio.NewScanner(strings.NewReader(pr.Body)))
	if len(prs) != 1 {
		return fmt.Errorf("Package update associated with invalid number of projects. Expected 1. Got %d", len(prs))
	}

	prjPr, err := o.gitea.GetPullRequest(prs[0].Org, prs[0].Repo, prs[0].Num)

	if err != nil {
		return fmt.Errorf("Cannot get PrjGit PR in processPullRequestSync. Err: %w", err)
	}

	common.PanicOnError(git.GitExec("", "clone", "--branch", prjPr.Head.Name, "--depth", "1", prjPr.Head.Repo.SSHURL, common.DefaultGitPrj))
	commitId, ok := git.GitSubmoduleCommitId(common.DefaultGitPrj, req.Repository.Name, prjPr.Head.Sha)

	if !ok {
		return fmt.Errorf("Cannot fetch submodule commit id in prjgit for '%s'", req.Repository.Name)
	}

	// nothing changed, still in sync
	if commitId == req.Pull_Request.Head.Sha {
		log.Println("commitID already match - nothing to do")
		return nil
	}

	log.Printf("different ids: '%s' vs. '%s'\n", req.Pull_Request.Head.Sha, commitId)

	commitMsg := fmt.Sprintf(`Sync PR

Update to %s`, req.Pull_Request.Head.Sha)

	log.Println("will create new commit msg:", commitMsg)

	// we need to update prjgit PR with the new head hash
	branchName := prGitBranchNameForPR(req)
	updateSubmoduleInPR(req, git)
	common.PanicOnError(git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", commitMsg))
	common.PanicOnError(git.GitExec(common.DefaultGitPrj, "push", "origin", "+HEAD:"+branchName))
	return nil
}
