package skills

import (
	"context"
	"testing"

	"github.com/stretchr/testify/require"
	contentstorestore "github.com/tidbcloud/AgentTeam/internal/store/content"
)

type scriptedSkillAuthority struct {
	rows []contentstorestore.Authority
	i    int
}

func (s *scriptedSkillAuthority) GetAuthority(context.Context, string, string, string) (contentstorestore.Authority, bool, error) {
	if len(s.rows) == 0 {
		return contentstorestore.Authority{State: contentstorestore.AuthorityStateLegacyActive}, false, nil
	}
	row := s.rows[s.i]
	if s.i < len(s.rows)-1 {
		s.i++
	}
	return row, true, nil
}

func (s *scriptedSkillAuthority) ListAuthoritiesForBindings(context.Context, string, string, []string) (map[string]contentstorestore.Authority, error) {
	return map[string]contentstorestore.Authority{}, nil
}

func TestSkillLegacyMutationUsesGenerationCASCutoff(t *testing.T) {
	authority := &scriptedSkillAuthority{rows: []contentstorestore.Authority{
		{State: contentstorestore.AuthorityStateLegacyActive, Generation: 7},
		{State: contentstorestore.AuthorityStateNativeActive, Generation: 8},
	}}
	service := &Service{contentAuthority: authority}
	route, err := service.beginSkillWrite(context.Background(), "ws_1", "skill_1")
	require.NoError(t, err)
	require.False(t, route.native)
	require.Equal(t, uint64(7), route.generation)
	require.ErrorIs(t, service.ensureSkillWriteCurrent(context.Background(), "ws_1", "skill_1", route), ErrConflict)
}

func TestSkillAuthorityUnknownStateFailsClosed(t *testing.T) {
	service := &Service{contentAuthority: &scriptedSkillAuthority{rows: []contentstorestore.Authority{{State: "ambiguous", Generation: 1}}}}
	_, err := service.beginSkillWrite(context.Background(), "ws_1", "skill_1")
	require.Error(t, err)
	require.Contains(t, err.Error(), "unknown skill content authority state")
}
