package service

import (
	"context"

	"github.com/pingcap/agent-git-service/internal/gitstore"
)

// ComparePR returns the ahead/behind/commit diff between two refs on a repo.
// Thin pass-through over the tenant Git capability.
func (s *Service) ComparePR(ctx context.Context, repoFullName, base, head string) (gitstore.DiffResult, error) {
	gitStore, err := s.GitForCtx(ctx)
	if err != nil {
		return gitstore.DiffResult{}, err
	}
	return gitStore.Compare(ctx, repoFullName, base, head)
}

// CanMergePR returns the GitHub-style mergeability token for a PR's
// base/head refs ("MERGEABLE", "CONFLICTING", "UNKNOWN"). Non-error return
// matches gitstore's signature — merge conflicts are not errors here.
// Missing or invalid tenant scope collapses to "UNKNOWN" so callers cannot
// accidentally query an ambient Git store.
func (s *Service) CanMergePR(ctx context.Context, repoFullName, baseBranch, headBranch string) string {
	gitStore, err := s.GitForCtx(ctx)
	if err != nil {
		return "UNKNOWN"
	}
	return gitStore.CanMerge(ctx, repoFullName, baseBranch, headBranch)
}

// SimulatePRMerge performs a dry-run three-way merge and returns the
// resulting tree's SHA, used to populate GraphQL's potentialMergeCommit.
func (s *Service) SimulatePRMerge(ctx context.Context, repoFullName, baseSHA, headSHA string) (string, error) {
	gitStore, err := s.GitForCtx(ctx)
	if err != nil {
		return "", err
	}
	return gitStore.SimulateMerge(ctx, repoFullName, baseSHA, headSHA)
}

// UpdatePRBranch merges (or rebases) the PR's base into its head branch.
// Returns the new head SHA. Caller should persist this on the PR record.
func (s *Service) UpdatePRBranch(ctx context.Context, opts gitstore.UpdatePRBranchOptions) (string, error) {
	gitStore, err := s.GitForCtx(ctx)
	if err != nil {
		return "", err
	}
	return gitStore.UpdatePRBranch(ctx, opts)
}

// RevertPRMerge creates a revert branch on the repo. Used by the
// revertPullRequest GraphQL mutation; the resulting branch is then handed
// to CreatePR to build the revert PR.
func (s *Service) RevertPRMerge(ctx context.Context, repoFullName, baseBranch, mergeCommitSHA, revertBranchName string) (string, error) {
	gitStore, err := s.GitForCtx(ctx)
	if err != nil {
		return "", err
	}
	return gitStore.RevertMerge(ctx, repoFullName, baseBranch, mergeCommitSHA, revertBranchName)
}
