package teamworkflow

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

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

func teamWorkflowETag(teamWorkflowID string, revision int64) string {
	teamWorkflowID = strings.TrimSpace(teamWorkflowID)
	return fmt.Sprintf(`"team-workflow:%s:%d"`, teamWorkflowID, revision)
}

func requireTeamWorkflowRevision(raw string, teamWorkflowID string) (int64, error) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return 0, api.NewHTTPErrorWithCode(http.StatusPreconditionRequired, "If-Match is required", "precondition_required")
	}
	if strings.HasPrefix(raw, "W/") || !strings.HasPrefix(raw, `"`) || !strings.HasSuffix(raw, `"`) || strings.Contains(raw, ",") {
		return 0, api.NewHTTPErrorWithCode(http.StatusBadRequest, "If-Match must contain exactly one strong Team Workflow ETag", "team_workflow_invalid_if_match")
	}
	prefix := "team-workflow:" + strings.TrimSpace(teamWorkflowID) + ":"
	value := strings.TrimSuffix(strings.TrimPrefix(raw, `"`), `"`)
	if !strings.HasPrefix(value, prefix) {
		return 0, api.NewHTTPErrorWithCode(http.StatusBadRequest, "If-Match is for the wrong Team Workflow resource", "team_workflow_invalid_if_match")
	}
	revision, err := strconv.ParseInt(strings.TrimPrefix(value, prefix), 10, 64)
	if err != nil || revision < 1 {
		return 0, api.NewHTTPErrorWithCode(http.StatusBadRequest, "If-Match contains an invalid Team Workflow revision", "team_workflow_invalid_if_match")
	}
	return revision, nil
}
