# AuthenticatedPregnancyDataProvider.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2025 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */
    package dk.nsp.mingraviditet.core.data.repository.overview

    import dk.nsp.mingraviditet.core.data.domain.pregnancyInfo.PregnancyInfoDomainModel
    import dk.nsp.mingraviditet.core.data.domain.pregnancyInfo.toDomain
    import dk.nsp.mingraviditet.core.data.domain.settings.AppPreferences
    import dk.nsp.mingraviditet.core.data.util.userAcceptedDataAgreement
    import dk.nsp.mingraviditet.core.datastore.PregnancyPreferencesDataSource
    import dk.nsp.mingraviditet.core.model.data.PregnancyInfo
    import dk.nsp.mingraviditet.core.network.pregnancyInfo.PregnancyInfoDataSource
    import dk.nsp.mingraviditet.core.shared.network.Dispatcher
    import dk.nsp.mingraviditet.core.shared.network.Loading
    import dk.nsp.mingraviditet.core.shared.network.MGDispatchers
    import dk.nsp.mingraviditet.core.shared.network.ResultWrapper
    import dk.nsp.mingraviditet.core.shared.network.Success
    import dk.nsp.mingraviditet.core.shared.network.asSuccessValueOrNull
    import dk.nsp.mingraviditet.core.shared.network.mapSuccess
    import dk.nsp.mingraviditet.core.shared.sessionManager.SessionManager
    import kotlinx.coroutines.CoroutineDispatcher
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.Deferred
    import kotlinx.coroutines.async
    import kotlinx.coroutines.coroutineScope
    import kotlinx.coroutines.flow.MutableStateFlow
    import kotlinx.coroutines.flow.SharingStarted
    import kotlinx.coroutines.flow.combine
    import kotlinx.coroutines.flow.first
    import kotlinx.coroutines.flow.flowOn
    import kotlinx.coroutines.flow.stateIn
    import kotlinx.coroutines.flow.transformLatest
    import kotlinx.coroutines.launch
    import java.time.LocalDate
    import javax.inject.Inject
    import javax.inject.Singleton

    @Singleton
    class AuthenticatedPregnancyDataProvider @Inject constructor(
        private val pregnancyPreferencesDataSource: PregnancyPreferencesDataSource,
        private val pregnancyDataSource: PregnancyInfoDataSource,
        private val sessionManager: SessionManager,
        @Dispatcher(MGDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,
    ) : PregnancyDataProvider {
        override val refreshTrigger: MutableStateFlow<Int> = MutableStateFlow(0)

        override var pregnancyInfo = combine(
            pregnancyPreferencesDataSource.data,
            sessionManager.isLoggedIn,
            refreshTrigger,
        ) { pregnancyData: PregnancyInfo, isLoggedIn: Boolean, _: Int ->
            pregnancyData to isLoggedIn
        }.transformLatest { (pregnancyInfo, isLoggedIn) ->
            if (!isLoggedIn) {
                emit(Loading)
                return@transformLatest
            }
            emit(Loading)
            coroutineScope {
                val result = getPregnancyData(
                    pregnancyData = pregnancyInfo,
                ).await()
                emit(result)
            }
        }
            .flowOn(ioDispatcher)
            .stateIn(
                scope = CoroutineScope(ioDispatcher),
                started = SharingStarted.Companion.Lazily,
                initialValue = Loading,
            )

        override fun CoroutineScope.getPregnancyData(pregnancyData: PregnancyInfo): Deferred<ResultWrapper<PregnancyInfoDomainModel>> =
            async(ioDispatcher) {
                val dueDate: LocalDate? = pregnancyData.expectedDueDate
                val dateOfBirth: LocalDate? = pregnancyData.dateOfBirth
                val dateOfTermination: LocalDate? = pregnancyData.pregnancyTerminated
                if (dueDate == null) {
                    return@async getDueDateAndUpdatePreferences(dateOfBirth, dateOfTermination).await()
                }
                val result: ResultWrapper<PregnancyInfoDomainModel> = getPregnancyDataFromDueDate(
                    estimatedDueDate = dueDate,
                    dateOfBirth = dateOfBirth,
                    dateOfTermination = dateOfTermination,
                ).await()
                if (dateOfBirth == null && dateOfTermination == null) {
                    updatePreferencesInBackground(dateOfBirth, dateOfTermination)
                }
                return@async result
            }

        private fun updatePreferencesInBackground(
            dateOfBirth: LocalDate?,
            dateOfTermination: LocalDate?,
        ) {
            CoroutineScope(ioDispatcher).launch {
                getDueDateAndUpdatePreferences(dateOfBirth, dateOfTermination).await()
            }
        }

        private fun CoroutineScope.getDueDateAndUpdatePreferences(
            dateOfBirth: LocalDate?,
            dateOfTermination: LocalDate?,
        ) = async(ioDispatcher) {
            val result: ResultWrapper<PregnancyInfoDomainModel> =
                fetchDueDateAndPregnancyInfo(dateOfBirth, dateOfTermination).await()
            if (sessionManager.isLoggedIn.value && result is Success) {
                val oldDueDate = pregnancyPreferencesDataSource.data.first().expectedDueDate
                val newDueDate = result.asSuccessValueOrNull()?.pregnancyState?.dueDateOrNull()
                if (oldDueDate != newDueDate) {
                    pregnancyPreferencesDataSource.setExpectedDueDate(
                        newDueDate,
                    )
                }
            }
            return@async result
        }

        private fun CoroutineScope.fetchDueDateAndPregnancyInfo(
            dateOfBirth: LocalDate?,
            dateOfTermination: LocalDate?,
        ): Deferred<ResultWrapper<PregnancyInfoDomainModel>> =
            async {
                with(pregnancyDataSource) {
                    fetchPregnancyInfo().await().mapSuccess {
                        val domainPregnancyInfo = it.toDomain(
                            dateOfBirth = dateOfBirth,
                            userIsAnonymous = false,
                            dateOfPregnancyTermination = dateOfTermination,
                        )
                        return@mapSuccess domainPregnancyInfo
                    }
                }
            }

        override fun CoroutineScope.getPregnancyDataFromDueDate(
            estimatedDueDate: LocalDate,
            dateOfBirth: LocalDate?,
            dateOfTermination: LocalDate?,
        ): Deferred<ResultWrapper<PregnancyInfoDomainModel>> = async {
            with(pregnancyDataSource) {
                return@with getPregnancyInfoFromDueDate(
                    date = estimatedDueDate,
                    anonymous = false,
                )
                    .await()
                    .mapSuccess {
                        it.toDomain(
                            dateOfBirth = dateOfBirth,
                            userIsAnonymous = false,
                            dateOfPregnancyTermination = dateOfTermination,
                        )
                    }
            }
        }

        override fun CoroutineScope.clearPregnancy(): Deferred<Unit> {
            return async(ioDispatcher) {
                pregnancyPreferencesDataSource.clearPregnancy()
            }
        }

        override fun canHandle(userPrefs: AppPreferences): Boolean {
            return userPrefs.userAcceptedDataAgreement()
        }

        override fun refreshPregnancyInfo() {
            refreshTrigger.value += 1
        }
    }