import Foundation
import SharedModels
import SwiftData

/// SRS rating for verb-level vocab practice. Mirrors `CourseReviewStore` but
/// keyed by `verbId` (the integer primary key on `Verb`).
struct VerbReviewStore {
    let context: ModelContext

    @discardableResult
    func fetchOrCreateReviewCard(verbId: Int) -> VerbReviewCard {
        let id = VerbReviewCard.makeId(verbId: verbId)
        let descriptor = FetchDescriptor<VerbReviewCard>(
            predicate: #Predicate<VerbReviewCard> { $0.id == id }
        )
        if let existing = (try? context.fetch(descriptor))?.first {
            return existing
        }
        let card = VerbReviewCard(verbId: verbId)
        context.insert(card)
        return card
    }

    func rate(verbId: Int, quality: ReviewQuality) {
        let card = fetchOrCreateReviewCard(verbId: verbId)
        let result = SRSEngine.review(
            quality: quality,
            currentEase: card.easeFactor,
            currentInterval: card.interval,
            currentReps: card.repetitions
        )
        card.easeFactor = result.easeFactor
        card.interval = result.interval
        card.repetitions = result.repetitions
        card.dueDate = SRSEngine.nextDueDate(interval: result.interval)
        card.lastReviewDate = Date()
        try? context.save()
    }
}
