package main

import (
	"fmt"
	"log"

	"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,
	)

	// TODO: fix this for config.Organization
	prjGit, err := o.gitea.CreateRepositoryIfNotExist(git, config.Organization, 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
	}

	prset, err := common.FetchPRSet(o.gitea, req.Repository.Owner.Username, req.Repository.Name, req.Number, config)
	if err != nil {
		return err
	}

	// request build review
	log.Println("num of current reviewers:", len(PR.RequestedReviewers))
	maintainers, err := common.FetchProjectMaintainershipData(o.gitea, config.Organization, config.GitProjectName, config.Branch)
	if err != nil {
		return err
	}

	return prset.AssignReviewers(o.gitea, maintainers)
}
