"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const WebsitePlugin_1 = require("./WebsitePlugin");
const PublishPlugin_1 = require("./PublishPlugin");
const node_fetch_1 = require("node-fetch");
const project_1 = require("../project");
const rootPath = process.env.DATA_FOLDER;
async function default_1(config, opts = {}) {
    const options = {
        gitUrl: process.env.SILEX_HOOK_GIT,
        buildUrl: process.env.SILEX_HOOK_BUILD,
        ...opts
    };
    config.on(WebsitePlugin_1.EVENT_WRITE_END, async ({ res, req, projectId, data }) => {
        if (options.gitUrl) {
            await hook(options.gitUrl, {
                path: (0, project_1.projectPath)(projectId),
                message: 'Change from Silex',
            });
        }
    });
    config.on(WebsitePlugin_1.EVENT_ASSET_WRITE_END, async ({ res, req, projectId, uploadDir, form, data }) => {
        if (options.gitUrl) {
            await hook(options.gitUrl, {
                path: (0, project_1.projectPath)(projectId),
                message: 'Change from Silex',
            });
        }
    });
    config.on(PublishPlugin_1.EVENT_PUBLISH_END, async ({ projectId, files, req, res }) => {
        if (options.buildUrl) {
            await hook(options.buildUrl);
        }
    });
}
exports.default = default_1;
async function hook(url, params = {}) {
    if (url) {
        const urlObj = new URL(url);
        console.log('Calling hook', { url });
        try {
            Object.keys(params)
                .forEach(key => urlObj.searchParams.append(key, params[key]));
            return (0, node_fetch_1.default)(urlObj.toString());
        }
        catch (error) {
            console.log('Hook call failed', { url, error });
            return null;
        }
    }
}
