import Foundation

@MainActor @Observable
final class TemplatesViewModel {
    var templates: [MealTemplate] = []
    var isLoading = true
    var errorMessage: String?
    var isLogging = false
    var loggedTemplateId: String?

    private let repo = FitnessRepository.shared

    func load() async {
        isLoading = true
        errorMessage = nil

        do {
            templates = try await repo.templates(forceRefresh: true)
        } catch {
            errorMessage = error.localizedDescription
        }

        isLoading = false
    }

    func logTemplate(_ template: MealTemplate, date: String, onComplete: @escaping () -> Void) async {
        isLogging = true
        loggedTemplateId = template.id

        do {
            try await repo.logTemplate(id: template.id, date: date)
            loggedTemplateId = nil
            onComplete()
        } catch {
            errorMessage = "Failed to log template: \(error.localizedDescription)"
            loggedTemplateId = nil
        }

        isLogging = false
    }

    var groupedTemplates: [String: [MealTemplate]] {
        Dictionary(grouping: templates, by: \.mealType)
    }
}
