"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdateEventWebhookTask = void 0;
const RopidGTFSRoutesRepository_1 = require("../../../ropid-gtfs/data-access/RopidGTFSRoutesRepository");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const HTTPFetchProtocolStrategy_1 = require("@golemio/core/dist/integration-engine/datasources/protocol-strategy/HTTPFetchProtocolStrategy");
const AbstractTaskJsonSchema_1 = require("@golemio/core/dist/integration-engine/workers/AbstractTaskJsonSchema");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const golemio_validator_1 = require("@golemio/core/dist/shared/golemio-validator");
const sequelize_1 = require("@golemio/core/dist/shared/sequelize");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const JISContainerToken_1 = require("../../ioc/JISContainerToken");
const UpdateEventWebhookTransformation_1 = require("../../transformations/UpdateEventWebhookTransformation");
const constants_1 = require("../constants");
const WEBHOOK_TIMEOUT_IN_SECONDS = 120;
let UpdateEventWebhookTask = class UpdateEventWebhookTask extends AbstractTaskJsonSchema_1.AbstractTaskJsonSchema {
    constructor(config, transformation, routesRepository) {
        super(constants_1.JIS_WORKER_NAME.toLowerCase());
        this.config = config;
        this.transformation = transformation;
        this.routesRepository = routesRepository;
        this.schema = new golemio_validator_1.JSONSchemaValidator("UpdateEventWebhookTask", {
            type: "array",
            items: {
                type: "object",
            },
        });
        this.queueName = "updateEventWebhook";
        this.queueTtl = 60 * 1000; // 1 minute
        this.commonHeaders = this.config.getValue("module.pid.jis.webhooks.eventUpdate.commonHeaders", {});
        this.targets = this.config.getValue("module.pid.jis.webhooks.eventUpdate.targets.*");
    }
    async execute(data) {
        const posts = [];
        for (const target of this.targets) {
            // filter out events that should not be exported to the target
            const filteredEvents = data.filter((event) => Object.values(target.allowed_orgs).includes(event.organization_name) &&
                Object.values(target.allowed_event_types).includes(event.type));
            if (filteredEvents.length === 0)
                continue;
            const transformedEvents = await this.fillMissingDataAndTransform(filteredEvents);
            const post = this.getTargetFetchStrategy(target, transformedEvents)
                .getRawData()
                .then((res) => this.validateResponse(res, target))
                .catch((err) => {
                if (err instanceof golemio_errors_1.GeneralError)
                    throw err;
                throw new golemio_errors_1.GeneralError(`Error while sending event update webhook to ${target.url}`, this.constructor.name, err);
            });
            posts.push(post);
        }
        await Promise.all(posts);
    }
    getTargetFetchStrategy(target, events) {
        const fetchSettings = {
            url: target.url,
            method: "POST",
            headers: {
                ...this.commonHeaders,
                ...target.headers,
            },
            body: JSON.stringify(events),
            timeoutInSeconds: WEBHOOK_TIMEOUT_IN_SECONDS,
            responseType: "text",
        };
        return new HTTPFetchProtocolStrategy_1.HTTPFetchProtocolStrategy(fetchSettings);
    }
    validateResponse(response, target) {
        if (response.meta.statusCode < 200 || response.meta.statusCode >= 300) {
            throw new golemio_errors_1.GeneralError(`Error while sending event update webhook to ${target.url} (unexpected status code)`, this.constructor.name, JSON.stringify(response), response.meta.statusCode);
        }
    }
    async fillMissingDataAndTransform(events) {
        const routeIds = Array.from(new Set(events.flatMap((event) => event.informed_entity?.routes?.map((route) => route.id) || [])));
        let routeRecords;
        try {
            routeRecords = await this.routesRepository["sequelizeModel"].findAll({
                where: {
                    route_id: { [sequelize_1.Op.in]: routeIds },
                },
                attributes: ["route_short_name", "route_long_name", "route_type", "route_id"],
                raw: true,
            });
        }
        catch (err) {
            if (err instanceof golemio_errors_1.GeneralError)
                throw err;
            throw new golemio_errors_1.GeneralError(`Error while getting route details from DB`, this.constructor.name, err);
        }
        const routeMap = new Map();
        for (const route of routeRecords) {
            routeMap.set(route.route_id, route);
        }
        const result = events.map((event) => {
            const routes = [];
            for (const r of event.informed_entity?.routes || []) {
                const routeData = routeMap.get(r.id);
                if (routeData) {
                    routes.push({
                        route_id: routeData.route_id,
                        route_short_name: routeData.route_short_name,
                        route_long_name: routeData.route_long_name,
                        route_type: routeData.route_type,
                    });
                }
            }
            return this.transformation.transformElement({ event, routes });
        });
        return result;
    }
};
exports.UpdateEventWebhookTask = UpdateEventWebhookTask;
exports.UpdateEventWebhookTask = UpdateEventWebhookTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.SimpleConfig)),
    __param(1, (0, tsyringe_1.inject)(JISContainerToken_1.JISContainerToken.UpdateEventWebhookTransformation)),
    __param(2, (0, tsyringe_1.inject)(JISContainerToken_1.JISContainerToken.RopidGTFSRoutesRepository)),
    __metadata("design:paramtypes", [Object, UpdateEventWebhookTransformation_1.UpdateEventWebhookTransformation,
        RopidGTFSRoutesRepository_1.RopidGTFSRoutesRepository])
], UpdateEventWebhookTask);
//# sourceMappingURL=UpdateEventWebhookTask.js.map