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);
};
import ComponentCode from "../../ComponentCode";
import HTTPErrorResponse from "../../../../../Types/API/HTTPErrorResponse";
import URL from "../../../../../Types/API/URL";
import APIException from "../../../../../Types/Exception/ApiException";
import BadDataException from "../../../../../Types/Exception/BadDataException";
import ComponentID from "../../../../../Types/Workflow/ComponentID";
import TelegramComponents from "../../../../../Types/Workflow/Components/Telegram";
import API from "../../../../../Utils/API";
import CaptureSpan from "../../../../Utils/Telemetry/CaptureSpan";
export default class SendMessageToChat extends ComponentCode {
    constructor() {
        super();
        const Component = TelegramComponents.find((i) => {
            return i.id === ComponentID.TelegramSendMessageToChat;
        });
        if (!Component) {
            throw new BadDataException("Component not found.");
        }
        this.setMetadata(Component);
    }
    async run(args, options) {
        var _a, _b, _c, _d, _e;
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "success";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Success port not found"));
        }
        const errorPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "error";
        });
        if (!errorPort) {
            throw options.onError(new BadDataException("Error port not found"));
        }
        if (!args["bot-token"]) {
            throw options.onError(new BadDataException("Telegram Bot Token not found"));
        }
        if (!args["chat-id"]) {
            throw options.onError(new BadDataException("Telegram Chat ID not found"));
        }
        if (!args["text"]) {
            throw options.onError(new BadDataException("Telegram message not found"));
        }
        const botToken = (_a = args["bot-token"]) === null || _a === void 0 ? void 0 : _a.toString();
        const chatId = (_b = args["chat-id"]) === null || _b === void 0 ? void 0 : _b.toString();
        const text = (_c = args["text"]) === null || _c === void 0 ? void 0 : _c.toString();
        const telegramApiUrl = URL.fromString(`https://api.telegram.org/bot${botToken}/sendMessage`);
        let apiResult = null;
        try {
            // https://core.telegram.org/bots/api#sendmessage
            apiResult = await API.post({
                url: telegramApiUrl,
                data: {
                    chat_id: chatId,
                    text: text,
                },
            });
            const helpMessage = " Note: For usernames, the user must have started a conversation with the bot first. For groups/channels, the bot must be added as a member or admin.";
            if (apiResult instanceof HTTPErrorResponse) {
                // Telegram returns errors in 'description' field
                const telegramError = ((_d = apiResult.data) === null || _d === void 0 ? void 0 : _d["description"]) ||
                    apiResult.message ||
                    "Server Error.";
                return Promise.resolve({
                    returnValues: {
                        error: telegramError + helpMessage,
                    },
                    executePort: errorPort,
                });
            }
            // Check if Telegram returned ok: false (some errors return 200 OK)
            if (apiResult.data && apiResult.data["ok"] === false) {
                const telegramError = apiResult.data["description"] || "Telegram API Error.";
                return Promise.resolve({
                    returnValues: {
                        error: telegramError + helpMessage,
                    },
                    executePort: errorPort,
                });
            }
            return Promise.resolve({
                returnValues: {},
                executePort: successPort,
            });
        }
        catch (err) {
            const helpMessage = " Note: For usernames, the user must have started a conversation with the bot first. For groups/channels, the bot must be added as a member or admin.";
            if (err instanceof HTTPErrorResponse) {
                // Telegram returns errors in 'description' field
                const telegramError = ((_e = err.data) === null || _e === void 0 ? void 0 : _e["description"]) ||
                    err.message ||
                    "Server Error.";
                return Promise.resolve({
                    returnValues: {
                        error: telegramError + helpMessage,
                    },
                    executePort: errorPort,
                });
            }
            throw options.onError(new APIException("Something wrong happened."));
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], SendMessageToChat.prototype, "run", null);
//# sourceMappingURL=SendMessageToChat.js.map