package outbound import ( "context" "errors" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) var ErrCompanyQuotaSnapshotChanged = errors.New("company quota snapshot changed") // CompanyQuotaDecision is the result of an atomic invitation or card-view // reservation. Reused means the same invitation or a recent view already // counted, so it is allowed without another usage charge. A denied decision // has Reused false and RetryAt set to the earliest expiry that can free room, // in UTC. type CompanyQuotaDecision struct { Allowed bool Reused bool RetryAt time.Time } // CompanyQuotaRepository atomically reserves per-organization invitation and // candidate-card usage. Implementations are transaction-bound: a caller // creates the invitation or applies the visibility change in the same // transaction, so a failed business operation cannot leave quota charged. // // Writers lock rows in this order: organization, active membership, // invitation or visibility record, then quota usage. A repository may take an // organization lock again inside the same transaction, but must not invert // this order. Each method rechecks the organization's stored verification // level, basis, and changed_at against the snapshot in CompanyQuota before it // writes; a caller cannot grant itself a tier by supplying a different level. // // Invitation usage is keyed by organization and invitation ID and remains // until the organization is deleted. The unique key makes retries idempotent // even when they arrive with a different request idempotency key; pruning by // the rolling quota window would allow an old invitation to count again. // Card-view usage is keyed by organization and candidate, counts only when // last_seen is strictly after the rolling-window cutoff, and expires // logically at that boundary. Bounded cleanup is opportunistic after a // successful reservation, so physical row removal has no exact-time promise. // Repeated views update last_seen monotonically with the greater of the // stored and current times. type CompanyQuotaRepository interface { // ReserveInvitation counts a new invitation against the current policy // limit. An existing invitation ID is returned as allowed and reused // without a second charge, regardless of its age or the request key. A // denied new invitation writes no usage and reports RetryAt after the // earliest currently counted invitation expires. ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error) // ReserveCardView counts a distinct candidate within the rolling card-view // window. A repeat while the prior view is active is allowed and reused, // and refreshes last_seen with a monotonic update. A denied new view writes // no usage and reports RetryAt after the earliest active view expires. ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error) }