import Foundation

struct QueueEntry: Identifiable, Equatable, Codable {
    let id: UUID
    let source: QueueSource
    let title: String
    let artist: String
    let duration: Double

    init(id: UUID = UUID(), source: QueueSource, title: String, artist: String, duration: Double) {
        self.id = id
        self.source = source
        self.title = title
        self.artist = artist
        self.duration = duration
    }

    static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id }

    enum QueueSource: Equatable, Codable {
        case swiftDataTrack(trackPersistentID: String, isCloud: Bool, cloudStreamPath: String?)
        case cloudDirect(chadTrackId: String, streamPath: String)
    }

    var formattedDuration: String {
        let total = Int(duration)
        let minutes = total / 60
        let seconds = total % 60
        return String(format: "%d:%02d", minutes, seconds)
    }

    static func from(track: Track) -> QueueEntry {
        QueueEntry(
            source: .swiftDataTrack(
                trackPersistentID: track.id.uuidString,
                isCloud: track.isCloud,
                cloudStreamPath: track.cloudStreamPath
            ),
            title: track.title,
            artist: track.artist,
            duration: track.duration
        )
    }

    static func from(cloudTrack: ChadTrack) -> QueueEntry {
        QueueEntry(
            source: .cloudDirect(
                chadTrackId: cloudTrack.id,
                streamPath: cloudTrack.url
            ),
            title: cloudTrack.title,
            artist: cloudTrack.artist ?? "",
            duration: cloudTrack.duration ?? 0
        )
    }
}
