package shared

import (
	"context"
	"strings"

	"github.com/google/go-github/v62/github"
)

func CreateGitBranch(ctx context.Context, client *github.Client, owner, repo, branch, base string) error {
	master, _, err := client.Git.GetRef(ctx, owner, repo, "refs/heads/"+base)
	if err != nil {
		return err
	}
	branchRef := "refs/heads/" + branch
	_, _, err = client.Git.CreateRef(ctx, owner, repo, &github.Reference{
		Ref:    &branchRef,
		Object: master.Object,
	})
	// Allow updating existing branch
	if r, ok := err.(*github.ErrorResponse); !ok || r.Message != "Reference already exists" {
		return err
	}
	return nil
}

func CreatePullRequest(ctx context.Context, client *github.Client, owner, repo string, pr github.NewPullRequest) error {
	branch := "refs/heads/" + *pr.Head
	_, _, err := client.PullRequests.Create(ctx, owner, repo, &pr)
	if err, ok := err.(*github.ErrorResponse); ok {
		// Clean up PR branch if no change
		for _, e := range err.Errors {
			if strings.HasPrefix(e.Message, "No commits between") {
				_, err := client.Git.DeleteRef(ctx, owner, repo, branch)
				return err
			}
			if strings.HasPrefix(e.Message, "A pull request already exists") {
				return nil
			}
		}
	}
	return err
}
