package main

import (
	"fmt"

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

type PullRequestOpened struct {
	gitea common.Gitea
}

func (o *PullRequestOpened) Process(req *common.PullRequestWebhookEvent, git common.Git, config *common.AutogitConfig) error {
	// requests against project are not handled here
	if req.Repository.Name == config.GitProjectName {
		return nil
	}

	// create PrjGit branch for buidling the pull request
	branchName := prGitBranchNameForPR(req)
	commitMsg := fmt.Sprintf(`auto-created for %s

This commit was autocreated by %s
referencing

`+common.PrPattern,
		req.Repository.Owner.Username,
		req.Repository.Name,
		GitAuthor,
		req.Repository.Name,
		req.Pull_Request.Number,
	)

	prjGit, err := o.gitea.CreateRepositoryIfNotExist(git, *req.Repository.Owner, config.GitProjectName)
	if err != nil {
		return err
	}

	common.PanicOnError(git.GitExec("", "clone", "--depth", "1", prjGit.SSHURL, common.DefaultGitPrj))
	err = git.GitExec(common.DefaultGitPrj, "fetch", "origin", branchName+":"+branchName)
	if err != nil {
		common.PanicOnError(git.GitExec(common.DefaultGitPrj, "checkout", "-B", branchName, prjGit.DefaultBranch))
	} else {
		common.PanicOnError(git.GitExec(common.DefaultGitPrj, "checkout", branchName))
	}
	subList, err := git.GitSubmoduleList(common.DefaultGitPrj, "HEAD")
	common.PanicOnError(err)

	if id := subList[req.Repository.Name]; id != req.Pull_Request.Head.Sha {
		updateSubmoduleInPR(req, git)
		common.PanicOnError(git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", commitMsg))
		common.PanicOnError(git.GitExec(common.DefaultGitPrj, "push", "origin", "+HEAD:"+branchName))
	}

	PR, err := o.gitea.CreatePullRequestIfNotExist(prjGit, branchName, prjGit.DefaultBranch,
		fmt.Sprintf("Forwarded PR: %s", req.Repository.Name),
		fmt.Sprintf(`This is a forwarded pull request by %s
referencing the following pull request:

`+common.PrPattern,
			GitAuthor, req.Repository.Owner.Username, req.Repository.Name, req.Pull_Request.Number),
	)

	if err != nil {
		return err
	}

	// request build review
	for _, reviewer := range config.Reviewers {
		_, err := o.gitea.RequestReviews(PR, reviewer)
		if err != nil {
			return fmt.Errorf("Failed to create reviewer '%s' for request: %s/%s/%d   Err: %w", reviewer, PR.Base.Repo.Owner.UserName, PR.Base.Repo.Name, PR.Index, err)
		}
	}

	return nil
}
