import Foundation

struct ChatMessage: Identifiable {
    let messageId: Int
    let taskId: Int
    let senderUserId: Int
    let senderType: String // "customer" or "worker"
    let senderName: String
    let text: String
    let createdOn: Date
    let isRead: Bool

    var id: Int { messageId }

    /// Manual init for creating messages locally (e.g. WebSocket)
    init(messageId: Int, taskId: Int, senderUserId: Int, senderType: String,
         senderName: String, text: String, createdOn: Date, isRead: Bool = false) {
        self.messageId = messageId
        self.taskId = taskId
        self.senderUserId = senderUserId
        self.senderType = senderType
        self.senderName = senderName
        self.text = text
        self.createdOn = createdOn
        self.isRead = isRead
    }

    /// Decode directly from a [String: Any] dictionary
    init(json: [String: Any]) {
        messageId = WorkTask.parseInt(json["MessageID"] ?? json["messageId"]) ?? 0
        taskId = WorkTask.parseInt(json["TaskID"] ?? json["taskId"]) ?? 0
        senderUserId = WorkTask.parseInt(json["SenderUserID"] ?? json["senderUserId"]) ?? 0
        senderType = (json["SenderType"] as? String) ?? (json["senderType"] as? String) ?? "customer"
        senderName = (json["SenderName"] as? String) ?? (json["senderName"] as? String) ?? ""
        text = (json["Text"] as? String) ?? (json["MessageText"] as? String) ?? (json["text"] as? String) ?? ""

        let dateVal = json["CreatedOn"] ?? json["timestamp"]
        if let s = dateVal as? String {
            createdOn = APIService.parseDate(s) ?? Date()
        } else {
            createdOn = Date()
        }

        if let b = json["IsRead"] as? Bool { isRead = b }
        else if let i = json["IsRead"] as? Int { isRead = i == 1 }
        else if let b = json["isRead"] as? Bool { isRead = b }
        else { isRead = false }
    }

    func isMine(userType: String) -> Bool {
        senderType == userType
    }
}
