"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildRouter = void 0;
const tslib_1 = require("tslib");
const adminjs_1 = require("adminjs");
const path_1 = tslib_1.__importDefault(require("path"));
const errors_1 = require("./errors");
const logger_1 = require("./logger");
const lodash_1 = require("lodash");
const promises_1 = require("fs/promises");
const mime = tslib_1.__importStar(require("mime-types"));
const multipart_1 = tslib_1.__importDefault(require("@fastify/multipart"));
const INVALID_ADMIN_JS_INSTANCE = 'You have to pass an instance of AdminJS to the buildRouter() function';
const getFile = (fileField) => {
    if (!(fileField === null || fileField === void 0 ? void 0 : fileField.file)) {
        return null;
    }
    const { file, filename } = fileField;
    file.name = filename;
    return file;
};
const buildRouter = async (admin, fastifyApp) => {
    var _a;
    const { assets } = adminjs_1.Router;
    if (((_a = admin === null || admin === void 0 ? void 0 : admin.constructor) === null || _a === void 0 ? void 0 : _a.name) !== 'AdminJS') {
        throw new errors_1.WrongArgumentError(INVALID_ADMIN_JS_INSTANCE);
    }
    await fastifyApp.register(multipart_1.default, { attachFieldsToBody: true });
    admin.initialize().then(() => {
        logger_1.log.debug('AdminJS: bundle ready');
    });
    const { routes } = adminjs_1.Router;
    routes.forEach(route => {
        // we have to change routes defined in AdminJS from {recordId} to :recordId
        const path = route.path.replace(/{/g, ':').replace(/}/g, '');
        const handler = async (request, reply) => {
            var _a;
            const controller = new route.Controller({ admin }, (_a = request.session) === null || _a === void 0 ? void 0 : _a.adminUser);
            const { params, query } = request;
            const method = request.method.toLowerCase();
            const body = request.body;
            const fields = (0, lodash_1.fromPairs)(Object.keys((body !== null && body !== void 0 ? body : {})).map(key => {
                var _a;
                return [
                    key,
                    (_a = getFile(body[key])) !== null && _a !== void 0 ? _a : body[key].value,
                ];
            }));
            const html = await controller[route.action](Object.assign(Object.assign({}, request), { params,
                query, payload: fields !== null && fields !== void 0 ? fields : {}, method }), reply);
            if (route.contentType) {
                reply.type(route.contentType);
            }
            else if (typeof html === 'string') {
                reply.type('text/html');
            }
            if (html) {
                return reply.send(html);
            }
        };
        if (route.method === 'GET') {
            fastifyApp.get(`${admin.options.rootPath}${path}`, handler);
        }
        if (route.method === 'POST') {
            fastifyApp.post(`${admin.options.rootPath}${path}`, handler);
        }
    });
    assets.forEach(asset => {
        fastifyApp.get(`${admin.options.rootPath}${asset.path}`, async (_req, reply) => {
            const mimeType = mime.lookup(asset.src);
            const file = await (0, promises_1.readFile)(path_1.default.resolve(asset.src));
            if (mimeType) {
                return reply.type(mimeType).send(file);
            }
            return reply.send(file);
        });
    });
};
exports.buildRouter = buildRouter;
