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

export default class BannersController {
    private paginationService = new PaginationService(Banner)
    public async index({ request }: HttpContextContract) {
        const { page, perPage } = request.qs()
        const pagination = await this.paginationService.paginate(request.all())
        return pagination
    }

    public async store({ request, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const validationSchema = schema.create({
            title: schema.string(),
            img: schema.string(),
            link: schema.string.optional(),
            desc: schema.string.optional()
        })
        const validatedData = await request.validate({
            schema: validationSchema
        })
        const banner = await Banner.create(validatedData)
        return banner
    }

    public async show({ params }: HttpContextContract) {
        const banner = await Banner.findOrFail(params.id)
        return banner
    }

    public async update({ request, params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const validationSchema = schema.create({
            title: schema.string.optional(),
            img: schema.string.optional(),
            link: schema.string.optional(),
            desc: schema.string.optional()
        })
        const validatedData = await request.validate({
            schema: validationSchema
        })
        const banner = await Banner.findOrFail(params.id)
        banner.merge(validatedData)
        await banner.save()
        return banner
    }

    public async destroy({ params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const banner = await Banner.findOrFail(params.id)
        await banner.delete()
    }
}
