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

export default class CategoriesController {
    private paginationService = new PaginationService(Category)

    public async index({ request }: HttpContextContract) {
        return await this.paginationService.paginate(request.all())
    }

    public async store({ request, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const data = await request.validate({
            schema: schema.create({
                name: schema.string()
            })
        })
        return await Category.create(data)
    }

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

    public async update({ params, request, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const category = await Category.findOrFail(params.id)
        const data = await request.validate({
            schema: schema.create({
                name: schema.string(),
                sort: schema.number.optional(),
                desc: schema.string.optional()
            })
        })
        category.merge(data)
        return await category.save()
    }

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