import SwiftUI
import AVFoundation

@MainActor
class ChatViewModel: ObservableObject {
    @Published var messages: [ChatMessage] = []
    @Published var isMediaPrefetched: Bool = false

    func loadMessages() {
        messages = SharingData.message.messages
        prefetchMedia()
    }

    private func prefetchMedia() {
        let imageURLs = messages.filter { $0.type == 2 && $0.message != nil }.compactMap { $0.message }.compactMap { URL(string: $0) }
        let videoURLs = messages.filter { $0.type == 3 && $0.message != nil }.compactMap { $0.message }.compactMap { URL(string: $0) }

        Task {
            await withTaskGroup(of: Void.self) { group in
                for url in imageURLs {
                    group.addTask {
                        let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 10)
                        _ = try? await URLSession.shared.data(for: request)
                    }
                }

                for url in videoURLs {
                    group.addTask {
                        let asset = AVURLAsset(url: url)
                        do {
                            _ = try await asset.load(.isPlayable)
                        } catch {
                            print(debug: "Video loading failure: \(url)")
                        }
                    }
                }
            }

            isMediaPrefetched = true
        }
    }
}

