import Foundation
import GenAPI

public struct SearchResult: Equatable {
    public let clips: [Clip]
    public let users: [SimpleProfile]
    public let playlists: [Playlist]
}

extension SearchResult {
    init(_ remote: GenAPI.SearchResult) throws {
        let resultItems = remote.result.flatMap(\.value.result).compactMap(\.object)

        self.clips = resultItems.compactMap(\.generatedClipSchema).compactMap { try? Clip($0) }
        self.playlists = resultItems.compactMap(\.playlistSchema).compactMap { try? Playlist($0) }
        self.users = resultItems.compactMap(\.simpleProfileInfoSchema).compactMap { try? SimpleProfile($0) }
    }
}

extension BaseSearchResult.ResultItem.Object {
    var generatedClipSchema: GeneratedClipSchema? {
        guard case .generatedClipSchema(let generatedClipSchema) = self else {
            return nil
        }
        return generatedClipSchema
    }

    var playlistSchema: PlaylistSchema? {
        guard case .playlistSchema(let playlistSchema) = self else {
            return nil
        }
        return playlistSchema
    }

    var simpleProfileInfoSchema: SimpleProfileInfoSchema? {
        guard case .simpleProfileInfoSchema(let profileInfoSchema) = self else {
            return nil
        }
        return profileInfoSchema
    }
}
