import Foundation

@Observable
final class FitnessRepository {
    static let shared = FitnessRepository()

    private let api = FitnessAPI()

    var entries: [FoodEntry] = []
    var goal: DailyGoal?
    var foods: [Food] = []
    var recentFoods: [RecentFood] = []
    var templates: [MealTemplate] = []
    var isLoading = false
    var error: String?

    // MARK: - Entries

    func loadEntries(date: String) async {
        do {
            entries = try await api.getEntries(date: date)
        } catch {
            self.error = error.localizedDescription
        }
    }

    func loadGoal(date: String) async {
        do {
            goal = try await api.getGoalsForDate(date: date)
        } catch {
            goal = nil
        }
    }

    func createEntry(_ request: CreateEntryRequest) async throws -> FoodEntry {
        let entry = try await api.createEntry(request)
        await loadEntries(date: request.entryDate)
        return entry
    }

    func deleteEntry(id: String, date: String) async throws {
        _ = try await api.deleteEntry(id: id)
        await loadEntries(date: date)
    }

    // MARK: - Foods

    func loadFoods(limit: Int = 100) async {
        do {
            foods = try await api.getFoods(limit: limit)
        } catch {
            self.error = error.localizedDescription
        }
    }

    func searchFoods(query: String, limit: Int = 20) async throws -> [Food] {
        try await api.searchFoods(query: query, limit: limit)
    }

    func loadRecentFoods(limit: Int = 20) async {
        do {
            recentFoods = try await api.getRecentFoods(limit: limit)
        } catch {
            self.error = error.localizedDescription
        }
    }

    // MARK: - Templates

    func loadTemplates() async {
        do {
            templates = try await api.getTemplates()
        } catch {
            self.error = error.localizedDescription
        }
    }

    func logTemplate(id: String, mealType: String, entryDate: String) async throws -> TemplateLogResponse {
        try await api.logTemplate(id: id, mealType: mealType, entryDate: entryDate)
    }
}
