import Foundation
import Observation
import VelodyDomain
import VelodyNetworking
import VelodyPersistence
import VelodySync
import VelodyUtilities

@MainActor
@Observable
final class iPhoneLibraryViewModel {
    var tracks: [LibraryTrack] = []
    var syncStatus = "Offline library not synced yet"

    private let store = InMemoryLocalLibraryStore()
    private let keychainService = MemoryKeychainService()
    private let syncCoordinator: PlaceholderSyncCoordinator
    private var hasLoaded = false

    init() {
        let environment = ServerEnvironment(
            baseURL: URL(string: "http://localhost:3000")!,
            appVersion: "0.1.0"
        )
        let apiClient = StubVelodyAPIClient(environment: environment)
        self.syncCoordinator = PlaceholderSyncCoordinator(
            apiClient: apiClient,
            store: store
        )
    }

    func loadIfNeeded() async {
        guard !hasLoaded else { return }
        hasLoaded = true
        await keychainService.save("placeholder-bootstrap-token", forKey: "bootstrap-token")
        await refreshSync()
    }

    func refreshSync() async {
        do {
            let result = try await syncCoordinator.performInitialSync()
            tracks = result.tracks
            syncStatus = result.statusMessage
        } catch {
            syncStatus = "Sync placeholder failed: \(error.localizedDescription)"
        }
    }
}
