package com.example.livingai.data.local

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.livingai.domain.model.AnimalProfile

class AnimalDataPagingSource(
    private val dataSource: CSVDataSource
) : PagingSource<Int, AnimalProfile>() {

    override fun getRefreshKey(state: PagingState<Int, AnimalProfile>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AnimalProfile> {
        val page = params.key ?: 0
        
        return try {
            // Since CSVDataSource reads all lines at once currently (simulated simple DB),
            // we will paginate the list in memory.
            val allProfiles = dataSource.getAllAnimalProfiles()
            
            val start = page * params.loadSize
            val end = minOf(start + params.loadSize, allProfiles.size)
            
            if (start >= allProfiles.size) {
                 return LoadResult.Page(
                    data = emptyList(),
                    prevKey = if (page > 0) page - 1 else null,
                    nextKey = null
                )
            }
            
            val pagedData = allProfiles.subList(start, end)
            
            LoadResult.Page(
                data = pagedData,
                prevKey = if (page > 0) page - 1 else null,
                nextKey = if (end < allProfiles.size) page + 1 else null
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}
