package workspace

import (
	"context"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/require"

	"github.com/yan1h/agent-coding-workflow/internal/infra/git"
)

func newGitOpsSvc(t *testing.T) (*gitOpsService, *fakeRepo, *fakeGit, uuid.UUID) {
	t.Helper()
	pa := &fakePA{pid: uuid.New(), canRead: true, canWrite: true}
	gitr := &fakeGit{}
	repo := newFakeRepo()
	wsID := uuid.New()
	repo.wss[wsID] = &Workspace{ID: wsID, ProjectID: pa.pid, MainPath: "/data/main", DefaultBranch: "main"}
	cred := func(_ context.Context, _ uuid.UUID) (*git.Credential, error) {
		return &git.Credential{Kind: git.CredentialNone}, nil
	}
	svc := NewGitOpsService(repo, noopAudit{}, gitr, pa, cred).(*gitOpsService)
	return svc, repo, gitr, wsID
}

func TestGitOps_CommitOnMain_NoPush(t *testing.T) {
	t.Parallel()
	svc, _, _, wsID := newGitOpsSvc(t)
	sha, err := svc.CommitOnMain(context.Background(), Caller{UserID: uuid.New()}, wsID, CommitInput{Message: "x", AddAll: true})
	require.NoError(t, err)
	require.NotEmpty(t, sha)
}

func TestGitOps_CommitOnMain_WithPush(t *testing.T) {
	t.Parallel()
	svc, _, _, wsID := newGitOpsSvc(t)
	_, err := svc.CommitOnMain(context.Background(), Caller{UserID: uuid.New()}, wsID, CommitInput{Message: "x", Push: true, AddAll: true})
	require.NoError(t, err)
}

func TestGitOps_CommitOnWorktree(t *testing.T) {
	t.Parallel()
	svc, repo, _, wsID := newGitOpsSvc(t)
	wtID := uuid.New()
	repo.wts[wtID] = &Worktree{ID: wtID, WorkspaceID: wsID, Branch: "feat", Path: "/data/feat", Status: WorktreeStatusIdle}
	sha, err := svc.CommitOnWorktree(context.Background(), Caller{UserID: uuid.New()}, wtID, CommitInput{Message: "y", AddAll: true})
	require.NoError(t, err)
	require.NotEmpty(t, sha)
}

func TestGitOps_StatusOnMain(t *testing.T) {
	t.Parallel()
	svc, _, _, wsID := newGitOpsSvc(t)
	st, err := svc.StatusOnMain(context.Background(), Caller{UserID: uuid.New()}, wsID)
	require.NoError(t, err)
	require.Empty(t, st)
}
