import db from '@adonisjs/lucid/services/db';
import Project from '#models/project';
import Category from '#models/category';
import Tag from '#models/tag';
import Training from '#models/training';
import Experience from '#models/experience';
import Music from '#models/music';
import Information from '#models/information';
import Image from '#models/image';
import User from '#models/user';
import fs from 'node:fs/promises';
import { DateTime } from 'luxon';
export default class BackupController {
    async index({ view }) {
        return view.render('admin/backup/index');
    }
    async export({ response }) {
        const data = {
            projects: await Project.all(),
            categories: await Category.all(),
            tags: await Tag.all(),
            trainings: await Training.all(),
            experiences: await Experience.all(),
            musics: await Music.all(),
            information: await Information.all(),
            images: await Image.all(),
            users: await User.all(),
            project_tags: await db.from('project_tag').select('*'),
            project_trainings: await db.from('project_training').select('*'),
            experience_project: await db.from('experience_project').select('*'),
        };
        const date = new Date().toISOString().split('T')[0];
        return response.header('Content-type', 'application/json')
            .header('Content-disposition', `attachment; filename=backup_${date}.json`)
            .send(data);
    }
    async import({ request, response, session }) {
        const file = request.file('backup_file', {
            extnames: ['json'],
        });
        if (!file) {
            session.flashErrors({ error: 'Please upload a JSON file.' });
            return response.redirect().back();
        }
        if (file.hasErrors) {
            session.flashErrors({ error: file.errors[0].message });
            return response.redirect().back();
        }
        try {
            const fileContent = await fs.readFile(file.tmpPath, 'utf-8');
            const data = JSON.parse(fileContent);
            await db.transaction(async (trx) => {
                await trx.rawQuery('PRAGMA foreign_keys = OFF;');
                await trx.from('project_tag').delete();
                await trx.from('project_training').delete();
                await trx.from('experience_project').delete();
                await trx.from('projects').delete();
                await trx.from('categories').delete();
                await trx.from('tags').delete();
                await trx.from('trainings').delete();
                await trx.from('experiences').delete();
                await trx.from('music').delete();
                await trx.from('information').delete();
                await trx.from('images').delete();
                await trx.from('users').delete();
                const toSnakeCase = (arr) => arr.map((item) => {
                    const newItem = {};
                    for (const key in item) {
                        const snakeKey = key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
                        let val = item[key];
                        if (typeof val === 'string' && val.includes('T')) {
                            const parsed = DateTime.fromISO(val);
                            if (parsed.isValid) {
                                val = parsed.toFormat('yyyy-MM-dd HH:mm:ss');
                            }
                        }
                        newItem[snakeKey] = val;
                    }
                    return newItem;
                });
                if (data.categories?.length)
                    await trx.table('categories').multiInsert(toSnakeCase(data.categories));
                if (data.projects?.length)
                    await trx.table('projects').multiInsert(toSnakeCase(data.projects));
                if (data.tags?.length)
                    await trx.table('tags').multiInsert(toSnakeCase(data.tags));
                if (data.trainings?.length)
                    await trx.table('trainings').multiInsert(toSnakeCase(data.trainings));
                if (data.experiences?.length)
                    await trx.table('experiences').multiInsert(toSnakeCase(data.experiences));
                if (data.musics?.length)
                    await trx.table('music').multiInsert(toSnakeCase(data.musics));
                if (data.information?.length)
                    await trx.table('information').multiInsert(toSnakeCase(data.information));
                if (data.images?.length)
                    await trx.table('images').multiInsert(toSnakeCase(data.images));
                if (data.users?.length)
                    await trx.table('users').multiInsert(toSnakeCase(data.users));
                if (data.project_tags?.length)
                    await trx.table('project_tag').multiInsert(data.project_tags);
                if (data.project_trainings?.length)
                    await trx.table('project_training').multiInsert(data.project_trainings);
                if (data.experience_project?.length)
                    await trx.table('experience_project').multiInsert(data.experience_project);
                await trx.rawQuery('PRAGMA foreign_keys = ON;');
            });
            session.flash({ success: 'Database restored successfully.' });
        }
        catch (error) {
            console.error(error);
            session.flashErrors({ error: 'Failed to import backup: ' + error.message });
        }
        return response.redirect().back();
    }
}
//# sourceMappingURL=backup_controller.js.map