package outbound import ( "context" "errors" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) var ( // ErrAssessmentAttemptNotFound covers both an unknown attempt and one // owned by another candidate. ErrAssessmentAttemptNotFound = errors.New("assessment attempt not found") // ErrAssessmentAttemptConflict reports an active-attempt, quota, retry, or // availability constraint that prevented attempt creation. ErrAssessmentAttemptConflict = errors.New("assessment attempt conflicts with current state") // ErrAssessmentAttemptIdempotencyConflict reports reuse of one idempotency // key for a different canonical request body. ErrAssessmentAttemptIdempotencyConflict = errors.New("assessment attempt idempotency key was reused") // ErrAssessmentAttemptVersionConflict reports an attempt changed after the // caller read it. ErrAssessmentAttemptVersionConflict = errors.New("assessment attempt version changed") // ErrAssessmentAttemptResultNotFound reports a completed attempt with no // persisted immutable decision snapshot. ErrAssessmentAttemptResultNotFound = errors.New("assessment attempt result not found") ) // AssessmentAttemptIdempotencyScope is the server HMAC of the operation, // client key, and authenticated actor. Raw keys never reach the repository. type AssessmentAttemptIdempotencyScope [IdempotencyDigestSize]byte // AssessmentAttemptRequestFingerprint is the server HMAC of the canonical // request body. It cannot be used as an offline check of a submitted answer. type AssessmentAttemptRequestFingerprint [IdempotencyDigestSize]byte // AssessmentAttemptCreateOutcome is the immutable public result retained for // the idempotency window. A created response contains its typed allowlisted // projection; a conflict contains only a stable problem code. type AssessmentAttemptCreateOutcome struct { StatusCode int16 Response domain.AssessmentAttemptPublicSnapshot ProblemCode string } // AssessmentAttemptCreateResult marks whether the outcome came from the // immutable idempotency snapshot rather than a new command execution. type AssessmentAttemptCreateResult struct { Outcome AssessmentAttemptCreateOutcome Replayed bool } // AssessmentAttemptSessionResult is the original HTTP 200 public projection // for a session command, including an unchanged terminal attempt. type AssessmentAttemptSessionResult struct { Response domain.AssessmentAttemptPublicSnapshot Replayed bool } // AssessmentAttemptCommandOutcome is an immutable answer or finalize // response retained for the idempotency window. type AssessmentAttemptCommandOutcome struct { StatusCode int16 Response domain.AssessmentAttemptPublicSnapshot ProblemCode string PendingItemIDs []uuid.UUID } // AssessmentAttemptCommandResult marks whether the outcome is a replay. type AssessmentAttemptCommandResult struct { Outcome AssessmentAttemptCommandOutcome Replayed bool } // AssessmentActiveAttemptSummary is the only active-attempt data needed by // availability preflight. It intentionally excludes frozen task content. type AssessmentActiveAttemptSummary struct { ID domain.AssessmentAttemptID ExpiresAt time.Time } // AssessmentRootAvailabilitySummary contains lifecycle timestamps for one // root and the latest attempt in its correction chain. It is a private // candidate-scoped read model and contains no answers or task content. type AssessmentRootAvailabilitySummary struct { RootTargetGrade domain.GradeCode RootCreatedAt time.Time RootUpdatedAt time.Time RootExpiresAt time.Time RootState domain.AssessmentAttemptState RootOutcome domain.AssessmentAttemptOutcome RootChainDeadline time.Time LatestTargetGrade domain.GradeCode LatestUpdatedAt time.Time LatestExpiresAt time.Time LatestState domain.AssessmentAttemptState LatestOutcome domain.AssessmentAttemptOutcome LatestChainDeadline time.Time LatestPlatformError string } // AssessmentRootQuotaSnapshot is the current rolling-window count and the // earliest instant a new root slot opens, if the quota is currently full. type AssessmentRootQuotaSnapshot struct { Count int32 AvailableAt *time.Time } // AssessmentAttemptRepositories exposes the repository bound to a UnitOfWork // transaction. type AssessmentAttemptRepositories interface { AssessmentAttempts() AssessmentAttemptRepository } // AssessmentAttemptRepository persists complete attempt snapshots, frozen // item instances, and immutable idempotent outcomes. Implementations bind // every method to the surrounding unit of work and preserve candidate // ownership in their queries. type AssessmentAttemptRepository interface { // Create atomically inserts an attempt and its frozen items. The caller // holds the actor+specialization transaction lock and stores the result // snapshot before the unit of work commits. Create(ctx context.Context, attempt domain.AssessmentAttempt) error // LockScope serializes creation and quota checks for one candidate and // specialization. A nil specialization is the separate training scope. LockScope(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode) error // GetActiveForSpecialization returns the one active real attempt, if any. // The partial unique index remains the final concurrency guard. GetActiveForSpecialization(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (domain.AssessmentAttempt, bool, error) // GetActiveTraining returns the one active training attempt, if any. // Training remains outside real assessment quotas and categories. GetActiveTraining(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttempt, bool, error) // GetLatestRootForSpecialization returns the newest root attempt, optionally // restricted to one target grade, for retry and promotion intervals. GetLatestRootForSpecialization( ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, grade *domain.GradeCode, ) (domain.AssessmentAttempt, bool, error) // CountRootAttemptsSince counts root attempts for the supplied candidate // and optional specialization at or after since. Corrective and training // attempts never consume root quota. CountRootAttemptsSince(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode, since time.Time) (int32, error) // GetAvailabilityActiveAttempt reads the current real attempt without a // row lock or lifecycle update. GetAvailabilityActiveAttempt(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (AssessmentActiveAttemptSummary, bool, error) // ListAvailabilityRootSummaries returns recent eligible root attempts and // their latest correction-chain headers without locking or loading items. ListAvailabilityRootSummaries(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, since time.Time) ([]AssessmentRootAvailabilitySummary, error) // GetRootQuotaSnapshot returns a candidate-wide root quota view for one // policy window. availableAt is nil unless a new root is currently blocked. GetRootQuotaSnapshot(ctx context.Context, userID uuid.UUID, since, asOf time.Time, window time.Duration, maxAttempts int32) (AssessmentRootQuotaSnapshot, error) // ListDisclosedFamilyKeys returns families actually shown by root or // corrective attempts since the non-repeat boundary; frozen future items // are excluded. ListDisclosedFamilyKeys(ctx context.Context, userID uuid.UUID, since time.Time) ([]domain.AssessmentFamilyKey, error) // ListCorrectionChain returns the root and all its corrections in creation // order, with their frozen items, for domain eligibility validation. ListCorrectionChain(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, rootID domain.AssessmentAttemptID) ([]domain.AssessmentAttempt, error) // SaveCreateOutcome records the original 201 or 409 response under the // already-reserved idempotency scope. The generic IdempotencyRecord and // this outcome commit in the same transaction and share its 24-hour expiry. SaveCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCreateOutcome) error // DeleteExpiredOutcome replaces a typed outcome only after generic Reserve // created a new idempotency window for the same scope. DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error // GetCreateOutcome returns the immutable 201 or 409 response snapshot for a // live key. Missing data for a live generic idempotency record is an // integrity error, not a cache miss. GetCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCreateOutcome, error) // GetForCandidate is owner-scoped. An unknown or foreign attempt returns // ErrAssessmentAttemptNotFound and never changes session or attempt state. GetForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) // GetKindForCandidate reads the immutable kind without acquiring an attempt // row lock. Session commands use it before checking C3, then lock the row. GetKindForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptKind, error) // GetForCandidateForUpdate obtains the owner-scoped write lock for a command. // Callers must take any required consent lock before this row lock. GetForCandidateForUpdate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) // StartOrResumeSession performs the version check and session transition // atomically. It returns changed=false for an active-session repeat or a // terminal attempt; a matching key's original 200 is stored separately. StartOrResumeSession( ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID, expectedVersion int64, at time.Time, ) (domain.AssessmentAttempt, bool, error) // SaveAnswer atomically makes one unanswered frozen item immutable and // advances its owner-scoped attempt transition from current to next. SaveAnswer(ctx context.Context, current, next domain.AssessmentAttempt, itemID uuid.UUID) error // SaveTransition atomically stores a non-answer lifecycle transition after // a command has locked the attempt row. SaveTransition(ctx context.Context, current, next domain.AssessmentAttempt) error // SaveResult stores one typed immutable result in the same transaction as // the completed attempt transition. SaveResult(ctx context.Context, userID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) error // GetResult returns the immutable owner-scoped result snapshot. GetResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultSnapshot, error) // SaveSessionOutcome records the original 200 public projection for the // already-reserved idempotency scope. It shares the transaction and expiry // of the generic idempotency record. SaveSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, response domain.AssessmentAttemptPublicSnapshot) error // GetSessionOutcome returns the original 200 public projection for a live // key, even if the stored attempt has since changed. GetSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentAttemptPublicSnapshot, error) // SaveAnswerOutcome stores a successful answer response or deterministic // not-found/state-conflict problem for its idempotency scope. SaveAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error // GetAnswerOutcome returns the original typed answer outcome for a live key. GetAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error) // SaveFinalizeOutcome stores a successful finalize response or deterministic // not-found/state-conflict problem for its idempotency scope. SaveFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error // GetFinalizeOutcome returns the original typed finalize outcome for a live key. GetFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error) }