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

export default class MemershipsController {
    private paginationService = new PaginationService(Membership)

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

    public async store({ request }: HttpContextContract) {
        const data = await request.validate({
            schema: schema.create({
                userId: schema.number(),
                startAt: schema.date(),
                expireAt: schema.date()
            })
        })
        return await Membership.create(data as any)
    }

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

    public async destroy({ params }: HttpContextContract) {
        const membership = await Membership.findOrFail(params.id)
        await membership.delete()
    }

    public async my({ auth }: HttpContextContract) {
        const membership = Membership.query()
            .where('userId', auth.user!.id)
            .orderBy('expireAt', 'desc')
            .limit(1)
            .first()
        if (!membership) {
            throw new Exception('Membership not found', 404)
        }
        return membership
    }
}
