import app from '@adonisjs/core/services/app';
import Image from '#models/image';
import fs from 'node:fs';
export default class ImagesController {
    async index({ view }) {
        const images = await Image.query().orderBy('created_at', 'desc');
        return view.render('admin/images/index', { images });
    }
    async store({ request, response, session }) {
        const imageFile = request.file('image', {
            size: '5mb',
            extnames: ['jpg', 'png', 'jpeg', 'webp', 'gif'],
        });
        if (!imageFile) {
            session.flashErrors({ error: 'Please upload an image file.' });
            return response.redirect().back();
        }
        if (imageFile.hasErrors) {
            session.flashErrors({ error: imageFile.errors[0].message });
            return response.redirect().back();
        }
        await imageFile.move(app.makePath('public/uploads/images'));
        await Image.create({
            filePath: `/uploads/images/${imageFile.fileName}`,
            originalName: imageFile.clientName,
            mimeType: imageFile.type + '/' + imageFile.subtype,
            size: imageFile.size,
        });
        session.flash({ success: 'Image uploaded successfully.' });
        return response.redirect().back();
    }
    async destroy({ params, response, session }) {
        const image = await Image.findOrFail(params.id);
        const absolutePath = app.makePath('public' + image.filePath);
        if (fs.existsSync(absolutePath)) {
            fs.unlinkSync(absolutePath);
        }
        await image.delete();
        session.flash({ success: 'Image deleted successfully.' });
        return response.redirect().back();
    }
}
//# sourceMappingURL=images_controller.js.map