import Foundation

@MainActor @Observable
final class HistoryViewModel {
    var days: [HistoryDay] = []
    var isLoading = true
    var errorMessage: String?

    private let repo = FitnessRepository.shared
    private let numberOfDays = 14

    struct HistoryDay: Identifiable {
        let date: Date
        let dateString: String
        let entries: [FoodEntry]
        let goal: DailyGoal

        var id: String { dateString }

        var totalCalories: Double {
            entries.reduce(0) { $0 + $1.calories }
        }

        var totalProtein: Double {
            entries.reduce(0) { $0 + $1.protein }
        }

        var totalCarbs: Double {
            entries.reduce(0) { $0 + $1.carbs }
        }

        var totalFat: Double {
            entries.reduce(0) { $0 + $1.fat }
        }

        var entryCount: Int {
            entries.count
        }

        var calorieProgress: Double {
            guard goal.calories > 0 else { return 0 }
            return min(totalCalories / goal.calories, 1.0)
        }
    }

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

        var results: [HistoryDay] = []

        do {
            // Load past N days
            for i in 0..<numberOfDays {
                let date = Date().adding(days: -i)
                let dateString = date.apiDateString

                let entries = try await repo.entries(for: dateString, forceRefresh: i == 0)
                let goal = try await repo.goals(for: dateString)

                results.append(HistoryDay(
                    date: date,
                    dateString: dateString,
                    entries: entries,
                    goal: goal
                ))
            }
            days = results
        } catch {
            errorMessage = error.localizedDescription
            days = results // Show what we have
        }

        isLoading = false
    }
}
