package com.example.myapplication.api.repository

import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.model.toProductRemote
import com.example.myapplication.database.AppDb
import com.example.myapplication.database.dao.ProductDao
import com.example.myapplication.database.entities.Product
import com.example.myapplication.database.repository.OfflineProductRepository
import com.example.myapplication.database.repository.OfflineRemoteKeyRepository
import com.example.myapplication.database.repository.ProductRepository
import kotlinx.coroutines.flow.Flow

class ProductRestRepository(
    private val service: MyServerService,
    private val productDao: ProductDao,
    private val dbProductRepository: OfflineProductRepository,
    private val dbRemoteKeyRepository: OfflineRemoteKeyRepository,
    private val categoryRestRepository: RestCategoryRepository,
    private val database: AppDb
): ProductRepository {
    @OptIn(ExperimentalPagingApi::class)
    override fun getAll(): Flow<PagingData<Product>> = Pager(
        config = PagingConfig(
            pageSize = 8,
            prefetchDistance = 2,
            enablePlaceholders = true,
            initialLoadSize = 12,
            maxSize = 24
        ),
        remoteMediator = ProductRemoteMediator(
            service,
            dbProductRepository,
            dbRemoteKeyRepository,
            categoryRestRepository,
            database,
        ),
        pagingSourceFactory = {
            productDao.getAll()
        }
    ).flow

    override fun getById(id: Int): Flow<Product> = productDao.getById(id)

    @OptIn(ExperimentalPagingApi::class)
    override fun getByCategory(category_id: Int): Flow<PagingData<Product>> = Pager(
        config = PagingConfig(
            pageSize = 8,
            prefetchDistance = 2,
            enablePlaceholders = true,
            initialLoadSize = 12,
            maxSize = 24
        ),
        remoteMediator = ProductRemoteMediator(
            service,
            dbProductRepository,
            dbRemoteKeyRepository,
            categoryRestRepository,
            database,
        ),
        pagingSourceFactory = {
            productDao.getByCategory(category_id)
        }
    ).flow

    override suspend fun insert(product: Product) {
        service.createProduct(product.toProductRemote())
    }

    override suspend fun insertAll(products: List<Product>) = productDao.insertAll(products)

    override suspend fun clearProducts() = productDao.deleteAll()
}