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.NewCommentDto
import com.example.dtf.models.Comment
import com.example.dtf.repositories.ICommentRepository
import com.example.dtf.repositories.online.mediator.CommentMediator
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

class RestCommentRepository @Inject constructor(
    private val appDatabase: AppDatabase,
    private val serverService: ServerService
) : ICommentRepository {
    override suspend fun insert(comment: Comment) {
        serverService.createComment(
            comment = NewCommentDto(post_id = comment.post_id, content = comment.content)
        )
        appDatabase.commentDao().insert(comment)
    }

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

    @OptIn(ExperimentalPagingApi::class)
    override fun getByPost(postId: Int): Flow<PagingData<Comment>> = Pager(
        PagingConfig(
            pageSize = 5,
            enablePlaceholders = false,
        ),
        remoteMediator = CommentMediator(appDatabase, serverService, postId.toString()),
        pagingSourceFactory = { appDatabase.commentDao().getByPost(postId) }
    ).flow
}