import Foundation
import Observation

/// Tracks the user's currently selected dog across the app. Picked once,
/// reused everywhere (Heim, Tagebuch, Statistik, …). Persisted in UserDefaults.
@Observable
@MainActor
final class ActiveDogStore {
    var activeDogId: Int
    var dogs: [Dog] = []

    var activeDog: Dog? {
        dogs.first(where: { $0.id == activeDogId }) ?? dogs.first
    }

    init() {
        self.activeDogId = UserDefaults.standard.integer(forKey: "activeDogId")
    }

    func loadDogs() async {
        do {
            let fetched: [Dog] = try await APIClient.shared.get("/api/dogs")
            self.dogs = fetched
            if !fetched.contains(where: { $0.id == activeDogId }),
               let first = fetched.first {
                setActive(first.id)
            }
        } catch {
            print("ActiveDogStore loadDogs failed: \(error)")
        }
    }

    func setActive(_ dogId: Int) {
        activeDogId = dogId
        UserDefaults.standard.set(dogId, forKey: "activeDogId")
    }
}
