//
//  SDLSuperCodec.swift
//  punchnet
//
//  Created by 安礼成 on 2026/5/22.
//
import Foundation
import NIOCore

enum SDLSuperCodec {
    public static func decode(frame: ByteBuffer) -> SDLQUICInboundMessage? {
        var buffer = frame
        guard let type = buffer.readInteger(as: UInt8.self),
              let packetType = SDLPacketType(rawValue: type) else {
            return nil
        }
        
        switch packetType {
        case .welcome:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let welcome = try? SDLWelcome(serializedBytes: bytes) else {
                return nil
            }
            return .welcome(welcome)
            
        case .registerSuperAck:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let registerSuperAck = try? SDLRegisterSuperAck(serializedBytes: bytes) else {
                return nil
            }
            return .registerSuperAck(registerSuperAck)
        case .registerSuperNak:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let registerSuperNak = try? SDLRegisterSuperNak(serializedBytes: bytes) else {
                return nil
            }
            return .registerSuperNak(registerSuperNak)
        case .peerInfo:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let peerInfo = try? SDLPeerInfo(serializedBytes: bytes) else {
                return nil
            }
            return .peerInfo(peerInfo)
        case .policyResponse:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let policyResponse = try? SDLPolicyResponse(serializedBytes: bytes) else {
                return nil
            }
            return .policyReponse(policyResponse)
        case .arpResponse:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let arpResponse = try? SDLArpResponse(serializedBytes: bytes) else {
                return nil
            }
            return .arpResponse(arpResponse)
        case .event:
            guard let bytes = buffer.readBytes(length: buffer.readableBytes),
                  let event = try? SDLEvent(serializedBytes: bytes) else {
                SDLLogger.log("SDLSuperClient decode Event Error", for: .debug)
                return nil
            }
            return .event(event)
        case .pong:
            return .pong
        default:
            SDLLogger.log("SDLSuperClient decode miss type: \(type)", for: .debug)
            
            return nil
        }
    }
}
