package workspace

import (
	"context"
	"testing"

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

func TestWorktreeCreate_FiresIndexHookOnce(t *testing.T) {
	t.Parallel()
	svc, _, _, _, wsID := newWtSvc(t)

	var calls int
	var gotWS uuid.UUID
	var gotWT *uuid.UUID
	svc.SetIndexBuildHook(func(_ context.Context, w uuid.UUID, wt *uuid.UUID, _ string) error {
		calls++
		gotWS = w
		gotWT = wt
		return nil
	})

	wt, err := svc.Create(context.Background(), Caller{UserID: uuid.New()}, wsID, CreateWorktreeInput{Branch: "feat-idx"})
	require.NoError(t, err)
	require.Equal(t, 1, calls, "index hook must fire exactly once on worktree create")
	require.Equal(t, wsID, gotWS)
	require.NotNil(t, gotWT)
	require.Equal(t, wt.ID, *gotWT)
}

func TestWorktreeCreate_HookErrorDoesNotFailCreate(t *testing.T) {
	t.Parallel()
	svc, _, _, _, wsID := newWtSvc(t)
	svc.SetIndexBuildHook(func(context.Context, uuid.UUID, *uuid.UUID, string) error {
		return context.DeadlineExceeded // simulate enqueue failure
	})
	_, err := svc.Create(context.Background(), Caller{UserID: uuid.New()}, wsID, CreateWorktreeInput{Branch: "feat-e"})
	require.NoError(t, err, "hook failure must not fail worktree create")
}

func TestCommitOnMain_FiresSummaryHook(t *testing.T) {
	t.Parallel()
	svc, _, _, wsID := newGitOpsSvc(t)

	var calls int
	var gotSHA, gotBranch string
	var gotWT *uuid.UUID
	svc.SetCommitSummaryHook(func(_ context.Context, _ uuid.UUID, wt *uuid.UUID, branch, sha string) error {
		calls++
		gotBranch, gotSHA, gotWT = branch, sha, wt
		return nil
	})

	sha, err := svc.CommitOnMain(context.Background(), Caller{UserID: uuid.New()}, wsID, CommitInput{Message: "m", AddAll: true})
	require.NoError(t, err)
	require.Equal(t, 1, calls)
	require.Equal(t, sha, gotSHA)
	require.Equal(t, "main", gotBranch)
	require.Nil(t, gotWT, "main commits carry no worktree id")
}
