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") // ErrAssessmentCategoryConflict reports a current category that could not // be advanced under its owner and specialization lock. ErrAssessmentCategoryConflict = errors.New("assessment category changed concurrently") ) // 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 } // AssessmentAttemptResultCursor is the keyset boundary for owner history. // It is internal to the repository; the usecase wraps it in an owner-bound // authenticated token before accepting it from HTTP. type AssessmentAttemptResultCursor struct { DecidedAt time.Time AttemptID domain.AssessmentAttemptID } // AssessmentAttemptResultRecord contains one immutable result and the owner // returned by the scoped query. The usecase rechecks ownership and eligibility. type AssessmentAttemptResultRecord struct { UserID uuid.UUID Entry domain.AssessmentAttemptResultHistoryEntry } type AssessmentAttemptResultPage struct { Records []AssessmentAttemptResultRecord HasMore bool } // 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) // SaveResultHistoryEntry stores a typed v1 or v2 immutable result. V1 keeps // the original result document; v2 carries category decision columns. SaveResultHistoryEntry(ctx context.Context, userID uuid.UUID, entry domain.AssessmentAttemptResultHistoryEntry) error // GetResultHistoryEntry returns the exact stored v1/v2 record without // reconstructing category information from current state. GetResultHistoryEntry(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultHistoryEntry, error) // ListCandidateAssessmentResults returns an owner-scoped keyset page and at // most limit entries. HasMore indicates that the repository found one more. ListCandidateAssessmentResults( ctx context.Context, userID uuid.UUID, cursor *AssessmentAttemptResultCursor, limit int32, ) (AssessmentAttemptResultPage, error) // LockCandidateCategory serializes one candidate/specialization upgrade. // Call only after consent, candidate/specialization, and attempt locks. LockCandidateCategory(ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode) error GetCandidateCategory( ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode, ) (domain.CandidateAssessmentCategory, bool, error) // GetSyntheticCategoryReview requires the complete immutable opening and // product-policy pins; gradingPolicyID must match the opening's policy. GetSyntheticCategoryReview( ctx context.Context, openingID uuid.UUID, category domain.AssessmentCategory, openingManifestHash [32]byte, productPolicyID domain.PolicyVersionID, productPolicyVersion int32, gradingPolicyID domain.PolicyVersionID, ) (domain.AssessmentSyntheticCategoryReview, bool, error) // CreateSyntheticCategoryReview stores an operator-attributed immutable // attestation after the domain has validated its explicit synthetic source. // It reports false, and stores nothing, when an attestation of the same // opening, manifest, and policy already exists, also when a concurrent // transaction created it; the caller then reads the stored one. CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) (bool, error) // SaveCandidateAssessmentCategory writes only an assigned category upgrade. SaveCandidateAssessmentCategory(ctx context.Context, category domain.CandidateAssessmentCategory) 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) }