package com.github.nullptroma.wallenc.app.di.modules.data

import android.content.Context
import com.github.nullptroma.wallenc.app.di.modules.app.IoDispatcher
import com.github.nullptroma.wallenc.domain.interfaces.IUnlockManager
import com.github.nullptroma.wallenc.domain.interfaces.IVault
import com.github.nullptroma.wallenc.domain.interfaces.IVaultsManager
import com.github.nullptroma.wallenc.domain.vault.network.yandexdisk.repository.YandexDiskRepositoryFactory
import com.github.nullptroma.wallenc.domain.vault.network.yandexuserinfo.repository.YandexUserInfoRepository
import com.github.nullptroma.wallenc.domain.vault.ports.StorageKeyMapStore
import com.github.nullptroma.wallenc.domain.vault.ports.YandexAccountStore
import com.github.nullptroma.wallenc.domain.vault.vaults.VaultsManager
import com.github.nullptroma.wallenc.domain.vault.vaults.local.LocalVault
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object VaultModule {

    @Provides
    @Singleton
    fun provideLocalVault(
        @IoDispatcher ioDispatcher: CoroutineDispatcher,
        @ApplicationContext context: Context,
    ): IVault = LocalVault(
        ioDispatcher = ioDispatcher,
        // getExternalFilesDir may return null before storage is ready; LocalVault handles null root.
        vaultRoot = context.getExternalFilesDir("LocalVault"),
    )

    @Provides
    @Singleton
    fun provideVaultsManager(
        @IoDispatcher ioDispatcher: CoroutineDispatcher,
        localVault: IVault,
        keyRepo: StorageKeyMapStore,
        yandexAccountStore: YandexAccountStore,
        yandexUserInfoRepository: YandexUserInfoRepository,
        yandexDiskRepositoryFactory: YandexDiskRepositoryFactory,
    ): VaultsManager = VaultsManager(
        ioDispatcher = ioDispatcher,
        localVault = localVault,
        keyRepo = keyRepo,
        yandexAccountStore = yandexAccountStore,
        yandexUserInfoRepository = yandexUserInfoRepository,
        yandexDiskRepositoryFactory = yandexDiskRepositoryFactory,
    )

    @Provides
    @Singleton
    fun provideUnlockManager(vaultsManager: IVaultsManager): IUnlockManager =
        vaultsManager.unlockManager
}
