import Foundation
import SwiftData
import Observation

@MainActor
@Observable
final class StudyTimerService {
    private(set) var sessionStart: Date?
    private(set) var tick: Int = 0
    private var timer: Timer?

    var isRunning: Bool { sessionStart != nil }

    /// Seconds elapsed in the current live session.
    var currentSessionSeconds: Int {
        // Access `tick` so SwiftUI re-evaluates each second.
        _ = tick
        guard let start = sessionStart else { return 0 }
        return max(0, Int(Date().timeIntervalSince(start)))
    }

    func start() {
        guard sessionStart == nil else { return }
        sessionStart = Date()
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            Task { @MainActor in
                self?.tick += 1
            }
        }
    }

    func stop(context: ModelContext) {
        guard let start = sessionStart else { return }
        let elapsed = max(0, Int(Date().timeIntervalSince(start)))
        sessionStart = nil
        timer?.invalidate()
        timer = nil

        guard elapsed > 0 else { return }

        let todayString = DailyLog.todayString()
        let log = ReviewStore.fetchOrCreateDailyLog(dateString: todayString, context: context)
        log.studySeconds += elapsed
        try? context.save()
    }
}
