package xrpc

import (
	"fmt"
	"net/http"
	"os/exec"
	"strings"

	"github.com/bluesky-social/indigo/atproto/atclient"
	"github.com/bluesky-social/indigo/atproto/syntax"
	"tangled.org/core/api/tangled"
)

func (x *Xrpc) GetMergeBase(w http.ResponseWriter, r *http.Request) {
	var (
		repoQuery = r.URL.Query().Get("repo")
		base      = r.URL.Query().Get("base")
		head      = r.URL.Query().Get("head")
	)

	repo, err := syntax.ParseDID(repoQuery)
	if err != nil {
		writeJson(w, http.StatusBadRequest, atclient.ErrorBody{Name: "BadRequest", Message: fmt.Sprintf("repo parameter invalid: %s", repoQuery)})
		return
	}

	if base == "" {
		writeJson(w, http.StatusBadRequest, atclient.ErrorBody{Name: "BadRequest", Message: "missing base parameter"})
		return
	}
	if head == "" {
		writeJson(w, http.StatusBadRequest, atclient.ErrorBody{Name: "BadRequest", Message: "missing head parameter"})
		return
	}

	l := x.logger.With("method", "git.getMergeBase", "repo", repo, "base", base, "head", head)
	l.Debug("request")

	ctx := r.Context()

	repoPath, err := x.makeRepoPath(ctx, repo)
	if err != nil {
		writeJson(w, http.StatusNotFound, atclient.ErrorBody{Name: "RepoNotFound", Message: fmt.Sprintf("unknown repository: %q", repo)})
		return
	}

	cmd := exec.Command("git", "-C", repoPath, "merge-base", head, base)
	out, err := cmd.Output()
	if err != nil {
		writeJson(w, http.StatusInternalServerError, atclient.ErrorBody{Name: "InternalError", Message: "failed to compute merge-base"})
		return
	}

	writeJson(w, http.StatusOK, tangled.GitTempGetMergeBase_Output{
		Commit: strings.TrimSpace(string(out)),
	})
}
