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

export default class PlayHistoriesController {
    private paginationService = new PaginationService(PlayHistory)

    public async index({ request, auth }: HttpContextContract) {
        const page = await this.paginationService.paginate({
            ...request.all(),
            userId: auth.user!.id,
            order: 'updatedAt,desc'
        })
        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
    }

    public async store({ request, auth }: HttpContextContract) {
        const data: any = await request.validate({
            schema: schema.create({
                episodeId: schema.number(),
                duration: schema.number()
            })
        })

        const episode = await Episode.findOrFail(data.episodeId)
        const series = await Series.findOrFail(episode.seriesId)
        data.seriesId = series.id
        data.userId = auth.user!.id

        let history = await PlayHistory.query()
            .where('userId', auth.user!.id)
            .where('seriesId', data.seriesId)
            .first()
        if (history) {
            history.episodeId = data.episodeId
            history.duration = data.duration
            await history.save()
        } else {
            history = await PlayHistory.create({
                ...data,
                userId: auth.user!.id
            })
        }

        await Series.query().where('id', series.id).increment('playCount', 1)
        await Episode.query().where('id', episode.id).increment('playCount', 1)

        return history
    }

    public async show({ params }: HttpContextContract) {
        return await PlayHistory.findOrFail(params.id)
    }

    public async destroy({ params, bouncer }: HttpContextContract) {
        const playHistory = await PlayHistory.findOrFail(params.id)
        await bouncer.authorize('owner', playHistory)
        await playHistory.delete()
        return playHistory
    }
}
