import SwiftData
import Foundation

struct MissedCourseItem: Codable, Hashable, Sendable {
    let front: String
    let back: String
}

@Model
final class TestResult {
    var id: String = ""
    var courseName: String = ""
    var weekNumber: Int = 0
    var quizType: String = ""
    var totalQuestions: Int = 0
    var correctCount: Int = 0
    var dateTaken: Date = Date()

    // Legacy CloudKit array-backed fields retained for migration compatibility.
    var missedFronts: [String] = []
    var missedBacks: [String] = []
    var missedItemsBlob: String = ""

    var scorePercent: Int {
        guard totalQuestions > 0 else { return 0 }
        return Int(round(Double(correctCount) / Double(totalQuestions) * 100))
    }

    init(courseName: String, weekNumber: Int, quizType: String, totalQuestions: Int, correctCount: Int, missedItems: [MissedCourseItem]) {
        self.id = UUID().uuidString
        self.courseName = courseName
        self.weekNumber = weekNumber
        self.quizType = quizType
        self.totalQuestions = totalQuestions
        self.correctCount = correctCount
        self.dateTaken = Date()
        self.missedItems = missedItems
    }

    convenience init(courseName: String, weekNumber: Int, quizType: String, totalQuestions: Int, correctCount: Int, missedFronts: [String], missedBacks: [String]) {
        self.init(
            courseName: courseName,
            weekNumber: weekNumber,
            quizType: quizType,
            totalQuestions: totalQuestions,
            correctCount: correctCount,
            missedItems: zip(missedFronts, missedBacks).map { MissedCourseItem(front: $0.0, back: $0.1) }
        )
    }

    var missedItems: [MissedCourseItem] {
        get {
            guard !missedItemsBlob.isEmpty,
                  let data = missedItemsBlob.data(using: .utf8),
                  let values = try? JSONDecoder().decode([MissedCourseItem].self, from: data) else {
                return zip(missedFronts, missedBacks).map { MissedCourseItem(front: $0.0, back: $0.1) }
            }
            return values
        }
        set {
            guard let data = try? JSONEncoder().encode(newValue),
                  let string = String(data: data, encoding: .utf8) else {
                missedItemsBlob = "[]"
                return
            }
            missedItemsBlob = string
            missedFronts = []
            missedBacks = []
        }
    }

    func migrateLegacyStorageIfNeeded() {
        if missedItemsBlob.isEmpty && (!missedFronts.isEmpty || !missedBacks.isEmpty) {
            missedItems = zip(missedFronts, missedBacks).map { MissedCourseItem(front: $0.0, back: $0.1) }
        }
    }
}
