package gitstore_test

import (
	"context"
	"testing"

	git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/pingcap/agent-git-service/internal/gitstore"
	"github.com/pingcap/agent-git-service/internal/testharness"
)

func initializeBareRepositoryFixture(store *gitstore.Store, ctx context.Context, fullName, defaultBranch string, seed bool) error {
	return testharness.InitializeBareRepositoryFixture(ctx, store, fullName, defaultBranch, seed)
}

func createBranchFixture(t testing.TB, store *gitstore.Store, ctx context.Context, fullName, branch, fromBranch string) error {
	t.Helper()
	path, err := store.GetRepoPath(ctx, fullName)
	if err != nil {
		return err
	}
	repository, err := git.PlainOpen(path)
	if err != nil {
		return err
	}
	reference, err := repository.Reference(plumbing.NewBranchReferenceName(fromBranch), true)
	if err != nil {
		return err
	}
	return repository.Storer.SetReference(plumbing.NewHashReference(plumbing.NewBranchReferenceName(branch), reference.Hash()))
}

func deleteReferenceFixture(t testing.TB, store *gitstore.Store, ctx context.Context, fullName, ref string) error {
	t.Helper()
	path, err := store.GetRepoPath(ctx, fullName)
	if err != nil {
		return err
	}
	repository, err := git.PlainOpen(path)
	if err != nil {
		return err
	}
	return repository.Storer.RemoveReference(plumbing.ReferenceName(ref))
}

func setReferenceFixture(t testing.TB, store *gitstore.Store, ctx context.Context, fullName, ref, sha string) error {
	t.Helper()
	path, err := store.GetRepoPath(ctx, fullName)
	if err != nil {
		return err
	}
	repository, err := git.PlainOpen(path)
	if err != nil {
		return err
	}
	return repository.Storer.SetReference(plumbing.NewHashReference(plumbing.ReferenceName(ref), plumbing.NewHash(sha)))
}
