import Foundation
import SwiftData

@Model
final class HistoryItem {
    
    let startDate: Date
    
    let message: Message
    
    let route: TransmissionType
    
    let finishDate: Date
    
    init(message: Message, startDate: Date, route: TransmissionType, finishDate: Date) {
        self.startDate = startDate
        self.message = message
        self.finishDate = finishDate
        self.route = route
    }
    
    var roundTripTime: TimeInterval {
        finishDate.timeIntervalSince(startDate)
    }
    
    var response: MessageResult {
        message.result
    }
}

extension HistoryItem: Identifiable {
    
    var id: Double {
        startDate.timeIntervalSince1970
    }
}

extension HistoryItem: Comparable {
    
    static func < (lhs: HistoryItem, rhs: HistoryItem) -> Bool {
        lhs.startDate < rhs.startDate
    }
}

extension HistoryItem {
    
    static var mock: HistoryItem {
        let message = Message(messageType: .request, clientChallenge: 123, serverChallenge: 234, result: .unlocked)
        return .init(
            message: message,
            startDate: Date.now.addingTimeInterval(-5),
            route: .throughServer,
            finishDate: Date.now)
    }
}
