package dev.adriankuta.flights.model.repository.usecases

import dev.adriankuta.flights.domain.search.ObserveAirportsUseCase
import dev.adriankuta.flights.domain.types.AirportInfo
import dev.adriankuta.flights.model.datasource.airports.AirportsDatasource
import dev.adriankuta.flights.model.datasource.airports.entities.AirportInfoModel
import dev.adriankuta.flights.model.repository.mappers.toDomain
import dev.adriankuta.flights.model.repository.utilities.loadData
import dev.adriankuta.model.data.api.AirportService
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject

internal class ObserveAirportsUseCaseImpl @Inject constructor(
    private val airportService: AirportService,
    private val airportsDatasource: AirportsDatasource,
) : ObserveAirportsUseCase {
    override fun invoke(): Flow<List<AirportInfo>?> = loadData(
        onCacheInvalidated = { cacheKey ->
            val response = airportService.getAirports("pl")
            airportsDatasource.setAirportsInfo(response, cacheKey)
        },
        observeCache = {
            airportsDatasource.airports
        },
        mapToDomain = {
            it.orEmpty().map(AirportInfoModel::toDomain)
        },
    )
}
