package com.syncflow.di

import android.content.Context
import androidx.room.Room
import androidx.work.WorkManager
import com.syncflow.data.db.*
import com.syncflow.data.preferences.AppPreferences
import com.syncflow.data.repository.AccountRepository
import com.syncflow.data.security.CredentialStore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

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

    @Provides @Singleton
    fun provideDatabase(@ApplicationContext ctx: Context): SyncDatabase =
        Room.databaseBuilder(ctx, SyncDatabase::class.java, "syncflow.db")
            .fallbackToDestructiveMigrationFrom(1)
            .addMigrations(SyncDatabase.MIGRATION_2_3, SyncDatabase.MIGRATION_3_4)
            .build()

    @Provides fun provideCloudAccountDao(db: SyncDatabase): CloudAccountDao = db.cloudAccountDao()
    @Provides fun provideSyncPairDao(db: SyncDatabase): SyncPairDao = db.syncPairDao()
    @Provides fun provideSyncFileStateDao(db: SyncDatabase): SyncFileStateDao = db.syncFileStateDao()
    @Provides fun provideSyncConflictDao(db: SyncDatabase): SyncConflictDao = db.syncConflictDao()
    @Provides fun provideSyncEventDao(db: SyncDatabase): SyncEventDao = db.syncEventDao()

    @Provides @Singleton
    fun provideCredentialStore(@ApplicationContext ctx: Context): CredentialStore =
        CredentialStore(ctx)

    @Provides @Singleton
    fun provideAccountRepository(
        accountDao: CloudAccountDao,
        credentialStore: CredentialStore,
    ): AccountRepository = AccountRepository(accountDao, credentialStore)

    @Provides @Singleton
    fun provideAppPreferences(@ApplicationContext ctx: Context): AppPreferences =
        AppPreferences(ctx)

    @Provides @Singleton
    fun provideWorkManager(@ApplicationContext ctx: Context): WorkManager =
        WorkManager.getInstance(ctx)
}
