import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import BalanceRecord from 'App/Models/BalanceRecord'
import Episode from 'App/Models/Episode'
import Series from 'App/Models/Series'
import PaginationService from 'App/Services/PaginationService'

export default class BalanceRecordsController {
    private paginationService = new PaginationService(BalanceRecord)
    public async index({ request, auth }: HttpContextContract) {
        const page = await this.paginationService.paginate({
            ...request.all(),
            userId: auth.user!.id
        })
        const seriesIds = new Set(
            page
                .all()
                .map((record) => record.seriesId)
                .filter((id) => !!id)
        )
        const series = await Series.findMany(Array.from(seriesIds))
        const episodeIds = new Set(
            page
                .all()
                .map((record) => record.episodeId)
                .filter((id) => !!id)
        )
        const episodes = await Episode.findMany(Array.from(episodeIds))
        page.all().forEach((record) => {
            if (record.seriesId) {
                record.series = series.find((s) => s.id === record.seriesId)
            }
            if (record.episodeId) {
                record.episode = episodes.find((e) => e.id === record.episodeId)
            }
        })
        return page
    }
}
