import APIClient
import ComposableArchitecture
import EventBusClient
import Foundation
import Utilities

private let log = Logger(category: "ModalClient")

// MARK: - ModalClient

public struct ModalClient {
    public var fetchModals: @Sendable () -> Void = { }
    public var markModalAsSeen: @Sendable (_ modalId: String) async -> Void = { _ in }
}

// MARK: - Dependency

public extension DependencyValues {
    var modalClient: ModalClient {
        get { self[ModalClient.self] }
        set { self[ModalClient.self] = newValue }
    }
}

// MARK: - Implementation

extension ModalClient: DependencyKey {
    public static let liveValue: Self = {
        return Self(
            fetchModals: {
                Task {
                    @Dependency(\.apiClientV2) var api
                    @Dependency(\.eventBus.sendModalEvent) var sendModalEvent

                    do {
                        let modals = try await api.getModals()
                        let imageUrls = modals.compactMap { modal -> URL? in
                            guard let urlString = modal.heroBackgroundImageUrlMobile else { return nil }
                            return URL(string: urlString)
                        }
                        if !imageUrls.isEmpty {
                            RemoteImagePrefetcher.shared.loadImages(urls: imageUrls)
                        }
                        sendModalEvent(.showModals(modals: modals))
                    } catch {
                        log.telemetry.error(error, message: "Failed to fetch modals from backend")
                    }
                }
            },
            markModalAsSeen: { modalId in
                Task {
                    @Dependency(\.apiClientV2) var api
                    do {
                        try await api.markModalAsSeen(modalId)
                    } catch {
                        log.telemetry.error(error, message: "Failed to mark modal as seen: \(modalId)")
                    }
                }
            }
        )
    }()
}
