import Foundation

@Observable
final class FoodSearchViewModel {
    private let repo = FitnessRepository.shared

    var searchText = ""
    var searchResults: [Food] = []
    var recentFoods: [RecentFood] = []
    var allFoods: [Food] = []
    var isSearching = false
    var isLoadingInitial = false
    var error: String?

    private var searchTask: Task<Void, Never>?

    func loadInitial() async {
        isLoadingInitial = true
        async let recentTask: () = loadRecent()
        async let allTask: () = loadAll()
        _ = await (recentTask, allTask)
        isLoadingInitial = false
    }

    private func loadRecent() async {
        await repo.loadRecentFoods(limit: 20)
        recentFoods = repo.recentFoods
    }

    private func loadAll() async {
        await repo.loadFoods(limit: 200)
        allFoods = repo.foods
    }

    func search() {
        searchTask?.cancel()
        let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !query.isEmpty else {
            searchResults = []
            return
        }
        isSearching = true
        searchTask = Task {
            try? await Task.sleep(for: .milliseconds(300))
            guard !Task.isCancelled else { return }
            do {
                let results = try await repo.searchFoods(query: query, limit: 20)
                if !Task.isCancelled {
                    searchResults = results
                }
            } catch {
                if !Task.isCancelled {
                    self.error = error.localizedDescription
                }
            }
            isSearching = false
        }
    }
}
