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'
import Drive from '@ioc:Adonis/Core/Drive'

export default class BannersController {
    private paginationService = new PaginationService(Banner)
    public async index({ request }: HttpContextContract) {
        const result = await this.paginationService.paginate(request.all())
        await Promise.all(
            result.map(async (banner) => {
                if (banner.img) {
                    const url = new URL(banner.img)
                    const filePath = url.pathname.replace(/^\//, '')
                    banner.img = await Drive.getSignedUrl(filePath)
                }
            })
        )
        return result
    }

    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)
        if (banner.img) {
            const url = new URL(banner.img)
            const filePath = url.pathname.replace(/^\//, '')
            banner.img = await Drive.getSignedUrl(filePath)
        }
        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()
    }
}
