"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const { generateWebhookID, getWebhookParams } = require("../../db/utils");
const toJsonSchema = require("to-json-schema");
const validate = require("jsonschema").validate;
const { WebhookType } = require("../../constants");
const triggers = require("../../automations/triggers");
const { getProdAppID } = require("@devlego/backend-core/db");
const { getAppDB, updateAppId } = require("@devlego/backend-core/context");
const AUTOMATION_DESCRIPTION = "Generated from Webhook Schema";
function Webhook(name, type, target) {
    this.live = true;
    this.name = name;
    this.action = {
        type,
        target,
    };
}
exports.Webhook = Webhook;
exports.fetch = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    const response = yield db.allDocs(getWebhookParams(null, {
        include_docs: true,
    }));
    ctx.body = response.rows.map(row => row.doc);
});
exports.save = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    const webhook = ctx.request.body;
    webhook.appId = ctx.appId;
    // check that the webhook exists
    if (webhook._id) {
        yield db.get(webhook._id);
    }
    else {
        webhook._id = generateWebhookID();
    }
    const response = yield db.put(webhook);
    webhook._rev = response.rev;
    ctx.body = {
        message: "Webhook created successfully",
        webhook,
    };
});
exports.destroy = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    ctx.body = yield db.remove(ctx.params.id, ctx.params.rev);
});
exports.buildSchema = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    yield updateAppId(ctx.params.instance);
    const db = getAppDB();
    const webhook = yield db.get(ctx.params.id);
    webhook.bodySchema = toJsonSchema(ctx.request.body);
    // update the automation outputs
    if (webhook.action.type === WebhookType.AUTOMATION) {
        let automation = yield db.get(webhook.action.target);
        const autoOutputs = automation.definition.trigger.schema.outputs;
        let properties = webhook.bodySchema.properties;
        // reset webhook outputs
        autoOutputs.properties = {
            body: autoOutputs.properties.body,
        };
        for (let prop of Object.keys(properties)) {
            autoOutputs.properties[prop] = {
                type: properties[prop].type,
                description: AUTOMATION_DESCRIPTION,
            };
        }
        yield db.put(automation);
    }
    ctx.body = yield db.put(webhook);
});
exports.trigger = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const prodAppId = getProdAppID(ctx.params.instance);
    yield updateAppId(prodAppId);
    try {
        const db = getAppDB();
        const webhook = yield db.get(ctx.params.id);
        // validate against the schema
        if (webhook.bodySchema) {
            validate(ctx.request.body, webhook.bodySchema);
        }
        const target = yield db.get(webhook.action.target);
        if (webhook.action.type === WebhookType.AUTOMATION) {
            // trigger with both the pure request and then expand it
            // incase the user has produced a schema to bind to
            yield triggers.externalTrigger(target, Object.assign(Object.assign({ body: ctx.request.body }, ctx.request.body), { appId: prodAppId }));
        }
        ctx.status = 200;
        ctx.body = {
            message: "Webhook trigger fired successfully",
        };
    }
    catch (err) {
        if (err.status === 404) {
            ctx.status = 200;
            ctx.body = {
                message: "Application not deployed yet.",
            };
        }
    }
});
