import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Property, { PropertyType } from 'App/Models/Property'
import PaginationService from 'App/Services/PaginationService'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
import { Exception } from '@adonisjs/core/build/standalone'

export default class PropertiesController {
    private paginationService = new PaginationService(Property)

    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(),
                value: schema.string(),
                remark: schema.string(),
                type: schema.enum(Object.values(PropertyType))
            })
        })

        return await Property.create(data)
    }

    public async show({ params, bouncer }: HttpContextContract) {
        // await bouncer.authorize('admin')
        return await Property.findOrFail(params.id)
    }

    public async findByName({ request }) {
        console.log(request)
        const data = await request.validate({
            schema: schema.create({
                name: schema.string()
            })
        })
        console.log(data)
        return await Property.findBy('name', data.name)
    }

    public async update({ request, params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        const data = await request.validate({
            schema: schema.create({
                name: schema.string.optional([]),
                remark: schema.string.optional(),
                value: schema.string.optional(),
                type: schema.enum(Object.values(PropertyType))
            })
        })
        const property = await Property.findOrFail(params.id)
        property.merge(data)
        await property.save()
        return property
    }

    public async destroy({ params, bouncer }: HttpContextContract) {
        await bouncer.authorize('admin')
        // const property = await Property.findOrFail(params.id)
        // await property.delete()
        throw new Exception('Not implemented', 501)
    }
}
