import Foundation
import VelodyDomain
import VelodyNetworking
import VelodyPersistence

public struct SyncResult: Hashable, Sendable {
    public var statusMessage: String
    public var tracks: [LibraryTrack]
    public var cursor: SyncCursor

    public init(
        statusMessage: String,
        tracks: [LibraryTrack],
        cursor: SyncCursor
    ) {
        self.statusMessage = statusMessage
        self.tracks = tracks
        self.cursor = cursor
    }
}

public protocol SyncCoordinator: Sendable {
    func performInitialSync() async throws -> SyncResult
}

public actor PlaceholderSyncCoordinator: SyncCoordinator {
    private let apiClient: any VelodyAPIClient
    private let store: any LocalLibraryStore

    public init(
        apiClient: any VelodyAPIClient,
        store: any LocalLibraryStore
    ) {
        self.apiClient = apiClient
        self.store = store
    }

    public func performInitialSync() async throws -> SyncResult {
        let health = try await apiClient.fetchHealthStatus()
        let existingTracks = await store.loadTracks()
        let tracks: [LibraryTrack]

        if existingTracks.isEmpty {
            tracks = [
                LibraryTrack(
                    title: "Velody Placeholder",
                    artist: "Private Library",
                    album: "Phase 1"
                ),
            ]
            await store.replaceTracks(tracks)
        } else {
            tracks = existingTracks
        }

        return SyncResult(
            statusMessage: "Sync placeholder ready (\(health.databaseStatus)/\(health.storageStatus))",
            tracks: tracks,
            cursor: SyncCursor(value: "0")
        )
    }
}
