"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EVENT_PUBLISH_END = exports.EVENT_PUBLISH_START = void 0;
const express = require("express");
const project_1 = require("../project");
const events_1 = require("../events");
const express_1 = require("../express");
const router = express.Router();
exports.EVENT_PUBLISH_START = 'EVENT_STARTUP_START';
exports.EVENT_PUBLISH_END = 'EVENT_PUBLISH_END';
async function default_1(config, opts = {}) {
    const options = {
        statusUrl: process.env.SILEX_PUBLICATION_STATUS_URL,
        ...opts,
    };
    config.on(events_1.EVENT_STARTUP_START, ({ app }) => {
        router.post('/publish', async function (req, res) {
            const { pages, files, projectId } = req.body.data;
            if (!pages || !projectId) {
                console.error('Error in the request, pages and projectId parmas required', { projectId });
                res.status(400).send({
                    message: 'Error in the request, pages and projectId parmas required',
                });
            }
            else {
                await config.emit(exports.EVENT_PUBLISH_START, { projectId, files, req });
                let url;
                try {
                    url = await (0, project_1.publish)(projectId, files, req.body.data);
                }
                catch (err) {
                    console.error('Error publishing the website', err);
                    res.status(500).json({ message: `Error publishing the website. ${err.message}` });
                    return;
                }
                const mutable = { projectId, files, req, res, url, statusUrl: options.statusUrl };
                await config.emit(exports.EVENT_PUBLISH_END, mutable);
                res.json({
                    url: mutable.url,
                    statusUrl: mutable.statusUrl,
                });
            }
        });
        app.use(express_1.noCache, router);
    });
}
exports.default = default_1;
