import Combine
import Foundation

/// DI-Container light – analog `AppContainer.kt` inkl. `ChatRepository`.
final class AppServices: ObservableObject {
    let api: RestAPIClient
    let socket: SocketClient
    let profileStore: ProfileStore
    let repository: ChatRepository

    private var cancellables = Set<AnyCancellable>()

    init() {
        let config = URLSessionConfiguration.default
        config.httpCookieStorage = .shared
        config.httpCookieAcceptPolicy = .always
        config.httpShouldSetCookies = true
        config.timeoutIntervalForRequest = 15
        config.timeoutIntervalForResource = 30
        let urlSession = URLSession(configuration: config)

        let api = RestAPIClient(baseURLString: AppConfig.baseURL, session: urlSession)
        let socket = SocketClient(baseURL: AppConfig.baseURL)
        let profileStore = ProfileStore()

        self.api = api
        self.socket = socket
        self.profileStore = profileStore
        self.repository = ChatRepository(api: api, socket: socket, profileStore: profileStore)

        repository.objectWillChange
            .receive(on: RunLoop.main)
            .sink { [weak self] _ in
                self?.objectWillChange.send()
            }
            .store(in: &cancellables)
    }
}
