package teamworkflow

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/api"
)

func requireTeamWorkflowHTTPError(t *testing.T, err error, status int, code string) {
	t.Helper()
	require.Error(t, err)
	var httpErr api.HTTPError
	require.ErrorAs(t, err, &httpErr)
	require.Equal(t, status, httpErr.Status)
	require.Equal(t, code, httpErr.Code)
}

func TestTeamWorkflowETagIsResourceScoped(t *testing.T) {
	require.Equal(t, `"team-workflow:twf_a:7"`, teamWorkflowETag("twf_a", 7))
	revision, err := requireTeamWorkflowRevision(teamWorkflowETag("twf_a", 7), "twf_a")
	require.NoError(t, err)
	require.Equal(t, int64(7), revision)

	_, err = requireTeamWorkflowRevision(teamWorkflowETag("twf_a", 7), "twf_b")
	requireTeamWorkflowHTTPError(t, err, http.StatusBadRequest, "team_workflow_invalid_if_match")
}

func TestTeamWorkflowMutationPreconditionsRejectMissingWeakAndAmbiguousETags(t *testing.T) {
	tests := []struct {
		name   string
		value  string
		status int
		code   string
	}{
		{name: "missing", status: http.StatusPreconditionRequired, code: "precondition_required"},
		{name: "weak", value: `W/"team-workflow:twf_a:7"`, status: http.StatusBadRequest, code: "team_workflow_invalid_if_match"},
		{name: "multiple", value: `"team-workflow:twf_a:7", "team-workflow:twf_a:8"`, status: http.StatusBadRequest, code: "team_workflow_invalid_if_match"},
		{name: "invalid revision", value: `"team-workflow:twf_a:zero"`, status: http.StatusBadRequest, code: "team_workflow_invalid_if_match"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			_, err := requireTeamWorkflowRevision(test.value, "twf_a")
			var httpErr api.HTTPError
			require.ErrorAs(t, err, &httpErr)
			require.Equal(t, test.status, httpErr.Status)
			require.Equal(t, test.code, httpErr.Code)
		})
	}
}
