import SwiftData
import Foundation

@Model
final class DailyLog {
    var id: String = ""
    var dateString: String = ""
    var reviewCount: Int = 0
    var correctCount: Int = 0
    var studySeconds: Int = 0

    var accuracy: Double {
        guard reviewCount > 0 else { return 0 }
        return Double(correctCount) / Double(reviewCount)
    }

    init(dateString: String, reviewCount: Int = 0, correctCount: Int = 0) {
        self.id = Self.makeID(dateString)
        self.dateString = dateString
        self.reviewCount = reviewCount
        self.correctCount = correctCount
    }

    static func makeID(_ dateString: String) -> String {
        dateString
    }

    func refreshIdentityIfNeeded() {
        let expected = Self.makeID(dateString)
        if id != expected {
            id = expected
        }
    }

    static func dateString(from date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }

    static func todayString() -> String {
        dateString(from: Date())
    }

    static func date(from string: String) -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.date(from: string)
    }
}
