import Foundation
import GenAPI

/*
 Shortcut used to display a link to a playlist in the Hooks tab carousel.
 This reuses existing paths that we have on Discover/Explore
 and is explicit with its destinations. The currently supported types are:
 - following
 - continue_listening
 - my_songs
 - liked_songs
 - playlist
 */
public struct Shortcut: Identifiable, Equatable, Hashable, Codable {
    public var id: String
    public var name: String
    public var description: String?
    public var imageUrl: String
    public var destination: ShortcutDestination

    public init(id: String, name: String, description: String? = nil, imageUrl: String, destination: ShortcutDestination) {
        self.id = id
        self.name = name
        self.description = description
        self.imageUrl = imageUrl
        self.destination = destination
    }
}

public enum ShortcutDestination: Codable, Equatable, Hashable {
    case library
    case likedSongs
    case playlistWithId(String)
    case followingPlaylist
    case continueListeningPlaylist
    case weeklyHitsPlaylist
    case discoverTab

    // Map from TabItemType to destination
    public static func from(type: TabItemType?, playlistId: String? = nil) -> ShortcutDestination? {
        guard let type = type else {
            if let playlistId = playlistId {
                return .playlistWithId(playlistId)
            }
            return nil
        }

        switch type.rawValue {
        case "following":
            return .followingPlaylist

        case "continue_listening":
            return .continueListeningPlaylist

        // TODO: Re-enable when we have this available
        // case "weekly_hits":
        //     return .weeklyHitsPlaylist

        case "my_songs":
            return .library

        case "liked_songs":
            return .likedSongs

        case "playlist":
            if let playlistId = playlistId {
                return .playlistWithId(playlistId)
            }
            return nil

        default:
            return nil // Don't show unmapped shortcuts
        }
    }
}

// MARK: - Conversion from API Schema

public extension Shortcut {
    init?(_ tabItem: TabItemSchema) {
        guard let destination = ShortcutDestination.from(type: tabItem.shortcutType, playlistId: tabItem.id) else {
            return nil // Don't create shortcuts for unmapped destinations
        }

        self.id = tabItem.id
        self.name = tabItem.name
        self.description = tabItem.description
        self.imageUrl = tabItem.imageUrl
        self.destination = destination
    }
}
