package com.example.dtf.repositories.online

import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.dtf.api.ServerService
import com.example.dtf.db.AppDatabase
import com.example.dtf.dto.EditPostDto
import com.example.dtf.dto.NewPostDto
import com.example.dtf.models.Post
import com.example.dtf.repositories.IPostRepository
import com.example.dtf.repositories.online.mediator.PostMediator
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

class RestPostRepository @Inject constructor(
    private val appDatabase: AppDatabase,
    private val serverService: ServerService
) : IPostRepository {
    override suspend fun insert(post: Post) {
        serverService.createPost(
            post = NewPostDto(post.title, post.content, post.category_id)
        )
    }

    override suspend fun update(post: Post) {
        serverService.updatePost(
            postId = post.id!!,
            post = EditPostDto(post.title, post.content)
        )
        appDatabase.postDao().update(post)
    }

    override fun getById(id: Int): Flow<Post> {
        return flow { emit(serverService.getPost(id)) }
    }

    @OptIn(ExperimentalPagingApi::class)
    override fun getByCategory(categoryId: Int): Flow<PagingData<Post>> = Pager(
        PagingConfig(
            pageSize = 4,
            enablePlaceholders = false
        ),
        remoteMediator = PostMediator(appDatabase, serverService, categoryId.toString()),
        pagingSourceFactory = { appDatabase.postDao().getByCategory(categoryId.toString()) }
    ).flow
}