//
//  LNRoomInfo.swift
//  Gami
//
//  Created by OneeChan on 2026/3/13.
//

import Foundation
import AtomicXCore

private let seatApplyCountKey = "mic_apply_num"
private let state_mic_mute = "state_mic_mute"

extension LiveInfo {
    var roomType: LNRoomType {
        guard let value = categoryList.first?.intValue else {
            return .unknown
        }
        return LNRoomType(rawValue: value)
    }
    
    var applySeatCount: Int {
        guard let value = metaData[seatApplyCountKey],
              let count = Int(value) else {
            return 0
        }
        return count
    }
    
    var forbidAudio: Bool {
        metaData[state_mic_mute] == "1"
    }
}

class LNRoomInfo {
    private var info: LiveInfo?
    var liveID: String = ""
    var liveName: String = ""
    var coverURL: String = ""
    var forbidAudio: Bool = false
    var owner: String = ""
    var roomType: LNRoomType = .unknown
    
    @discardableResult
    func update(_ info: LiveInfo) -> Bool {
        if info.liveID != liveID
            || info.liveName != liveName
            || info.coverURL != coverURL
            || info.liveOwner.userID != owner
            || info.forbidAudio != forbidAudio
            || info.roomType != roomType {
            let shouldFetch = liveID.isEmpty
            liveID = info.liveID
            liveName = info.liveName
            coverURL = info.coverURL
            owner = info.liveOwner.userID
            roomType = info.roomType
            forbidAudio = info.forbidAudio
            
            self.info = info
            
            if shouldFetch, info.metaData.isEmpty {
                // 退房冲进，会导致 metaData 丢失，需要主动拉取一次
                fetchMetaData()
            }
            
            return true
        }
        return false
    }
    
    private func fetchMetaData() {
        LNRoomManager.shared.liveListStore.queryMetaData(keys: [
            state_mic_mute
        ]) { [weak self] result in
            guard let self else { return }
            guard case .success(let info) = result,
                  let value = info[state_mic_mute]
            else {
                return
            }
            if self.info?.metaData.isEmpty == false {
                // 此时可能已经推送了新的数据
                return
            }
            forbidAudio = value == "1"
        }
    }
}
