package api

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

// MaxScopeNotificationAgentCursorParamBytes bounds the raw agentCursor
// query parameter accepted by notification panel GET routes. Generous relative
// to legitimate cursor JSON, tight enough to reject abuse.
const MaxScopeNotificationAgentCursorParamBytes = 1024

// MaxScopeNotificationAgentPageSize is the largest agentLimit the API layer
// accepts. Anything larger is rejected as 400 — the parser does not silently
// clamp. The store layer also clamps defensively in case a future internal
// caller bypasses the parser.
const MaxScopeNotificationAgentPageSize = 500

// ScopeNotificationAgentPage captures the optional agentCursor / agentLimit
// query parameters accepted by notification panel GET routes.
type ScopeNotificationAgentPage struct {
	Cursor string
	Limit  int
}

// ReadScopeNotificationAgentPage parses the optional agentCursor / agentLimit
// query parameters for paginated notification panel reads. agentCursor is
// treated as opaque (the store layer validates shape and canonical form);
// agentLimit must be a positive integer ≤ MaxScopeNotificationAgentPageSize
// when present. Errors map to HTTP 400.
//
// All three notification GET routes (/scopes/:scopeId/notifications,
// /channels/:channelId/notifications, /threads/:threadChannelId/notifications)
// share this parser so cursor semantics cannot drift between them.
func ReadScopeNotificationAgentPage(r WorkspaceScopedRequest) (ScopeNotificationAgentPage, error) {
	cursor := strings.TrimSpace(r.Gin.Query("agentCursor"))
	if cursor != "" && len(cursor) > MaxScopeNotificationAgentCursorParamBytes {
		return ScopeNotificationAgentPage{}, NewHTTPError(http.StatusBadRequest, "agentCursor is too long")
	}
	rawLimit := strings.TrimSpace(r.Gin.Query("agentLimit"))
	if rawLimit == "" {
		return ScopeNotificationAgentPage{Cursor: cursor}, nil
	}
	limit, err := strconv.Atoi(rawLimit)
	if err != nil || limit <= 0 {
		return ScopeNotificationAgentPage{}, NewHTTPError(http.StatusBadRequest, "agentLimit must be a positive integer")
	}
	if limit > MaxScopeNotificationAgentPageSize {
		return ScopeNotificationAgentPage{}, NewHTTPError(http.StatusBadRequest, "agentLimit exceeds the maximum page size")
	}
	return ScopeNotificationAgentPage{Cursor: cursor, Limit: limit}, nil
}
