package com.correx.core.validation.session

import com.correx.core.sessions.SessionStatus
import com.correx.core.validation.model.ValidationContext
import com.correx.core.validation.model.ValidationIssue
import com.correx.core.validation.model.ValidationSection
import com.correx.core.validation.model.ValidationSeverity
import com.correx.core.validation.pipeline.Validator

class SessionValidator : Validator {
    override suspend fun validate(context: ValidationContext): ValidationSection {

        val state = context.sessionState ?: return ValidationSection(
            name = "session",
            issues = emptyList()
        )

        val issues = mutableListOf<ValidationIssue>()

        val createdAt = state.createdAt
        val updatedAt = state.updatedAt

        // 1. temporal consistency
        if (createdAt != null && updatedAt != null) {
            if (createdAt > updatedAt) {
                issues += ValidationIssue(
                    code = "SESSION_TIME_INCONSISTENT",
                    message = "createdAt is after updatedAt",
                    severity = ValidationSeverity.ERROR
                )
            }
        }

        // 2. invalid transitions sanity
        if (state.invalidTransitions < 0) {
            issues += ValidationIssue(
                code = "SESSION_INVALID_TRANSITIONS_NEGATIVE",
                message = "invalidTransitions cannot be negative",
                severity = ValidationSeverity.ERROR
            )
        }

        // 3. status sanity (light semantic check only)
        if (state.status == SessionStatus.FAILED &&
            state.invalidTransitions == 0
        ) {

            issues += ValidationIssue(
                code = "SESSION_SUSPICIOUS_FAILURE_STATE",
                message = "FAILED session with zero invalid transitions",
                severity = ValidationSeverity.WARNING
            )
        }

        return ValidationSection(
            name = "session",
            issues = issues
        )
    }
}
