package outbound import ( "context" "errors" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) var ( // ErrSupportCaseNotFound covers both an unknown case and one owned by // another account. ErrSupportCaseNotFound = errors.New("support case not found") // ErrSupportCaseCreateOutcomeNotFound reports a live idempotency record // without its immutable create result. It is an integrity error, not a // public 404 response. ErrSupportCaseCreateOutcomeNotFound = errors.New("support case create outcome not found") // ErrSupportCaseConflict reports an appeal or another case that conflicts // with a still-current business rule. The repository leaves the // transaction usable so the caller can persist the immutable 409 outcome. ErrSupportCaseConflict = errors.New("support case conflicts with existing state") ) // MaxSupportCasePageSize matches the largest list page in the API contract. const MaxSupportCasePageSize = 100 // SupportCaseRepositories groups the ports that a create transaction must // bind to one unit of work. The caller also uses the existing idempotency // repository in that same transaction. type SupportCaseRepositories interface { SupportCases() SupportCaseRepository SupportCaseCreateOutcomes() SupportCaseCreateOutcomeRepository SupportCaseRequestLimits() SupportCaseRequestLimitRepository SupportCaseRubrics() SupportCaseRubricRepository } // SupportCaseRepository stores owner-private snapshots and their public // history. Implementations persist only the typed object reference, not a // copy of the referenced object, and every read names the owning account. type SupportCaseRepository interface { // NextNumber allocates a globally unique, never-reused display number for // the UTC year containing createdAt. The number is for display; case paths // use the UUID identifier. NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) // Create inserts the case and its complete initial public history in the // surrounding transaction. A failed create leaves neither committed. Create(ctx context.Context, supportCase domain.SupportCase) error // GetOwned returns the full case only when ownerID matches. Unknown and // foreign IDs both return ErrSupportCaseNotFound. GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) // ListOwned returns one page of summaries for ownerID, newest first by // CreatedAt and then ID. It never returns descriptions or event history. ListOwned(ctx context.Context, query SupportCaseListQuery) (SupportCaseListPage, error) } // SupportCaseCreateOutcomeRepository persists the original response for a // live generic idempotency scope. The stored case snapshot is immutable even // if the case later receives replies or changes status. type SupportCaseCreateOutcomeRepository interface { // DeleteCreateOutcome removes the expired result for a scope that the // generic idempotency repository has just accepted as new. It must run in // the same transaction as the replacement command. DeleteCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) error // SaveCreateOutcome stores a 201, 404, or domain state_conflict 409 result // in the surrounding transaction. Rejected validation, CSRF, rate-limit, // idempotency-in-progress, and key-reuse responses are not stored. The // scope is the HMAC digest from Idempotency-Key handling; raw keys and // request content never reach this port. SaveCreateOutcome( ctx context.Context, scope [IdempotencyDigestSize]byte, outcome domain.SupportCaseCreateOutcome, createdAt time.Time, ) error // GetCreateOutcome returns the original result for a live idempotency // scope, or ErrSupportCaseCreateOutcomeNotFound if the record is incomplete. GetCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.SupportCaseCreateOutcome, error) } // SupportCaseRequestLimitRepository enforces the per-account rolling request // budget. It is called after authentication, request validation, and account // scenario checks but before idempotency lookup or object resolution, so an // accepted replay and requests ending in 404 or 409 consume the same budget. // Implementations retain accepted request events for at least // domain.MaxSupportRequestWindow, even when the current product policy uses a // shorter window, so a later policy version can widen the window safely. // The use case must commit this counter for domain-level 400 and idempotency // 422 results that occur after this check, while leaving their create outcome // unstored; it returns those expected results as data and maps them to HTTP // only after the unit of work commits. type SupportCaseRequestLimitRepository interface { // LockOwner serializes the account's request-budget check before the // application timestamp is captured. The lock lasts until the enclosing // unit of work commits or rolls back. It returns the latest committed // request timestamp, or zero when the account has no request history, so a // temporarily regressing application clock cannot move the effective // window behind an event already counted. LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) // Consume records one qualifying request when the preceding rolling // window has fewer than maxRequests. The caller must acquire LockOwner // before supplying at. It returns Allowed=false and a // positive RetryAfter when the budget is exhausted. Rejected over-limit // requests do not increment the counter. Count only events with // requested_at > at-window and requested_at <= at; calculate RetryAfter // from the oldest event included in that count. Consume( ctx context.Context, ownerID uuid.UUID, at time.Time, maxRequests int32, window time.Duration, ) (SupportCaseRequestLimitResult, error) } // SupportCaseRequestLimitResult describes whether this request consumed a // slot in the account's rolling request budget. type SupportCaseRequestLimitResult struct { Allowed bool RetryAfter time.Duration } // SupportCaseListQuery selects one owner-scoped page. type SupportCaseListQuery struct { OwnerID uuid.UUID // After continues after the last item from the preceding page; nil reads // the newest cases. After *SupportCaseListPosition // Limit is from 1 to MaxSupportCasePageSize. Limit int32 } // SupportCaseListPosition is the descending order key for one list item. type SupportCaseListPosition struct { CreatedAt time.Time ID domain.SupportCaseID } // SupportCaseListPage is one page of summaries. HasMore is true when another // page follows and the caller can continue from the last item's position. type SupportCaseListPage struct { Items []domain.SupportCaseSummary HasMore bool } // SupportCasePositionOf returns the cursor position of an item from a page. func SupportCasePositionOf(item domain.SupportCaseSummary) SupportCaseListPosition { return SupportCaseListPosition{CreatedAt: item.CreatedAt, ID: item.ID} }