import UserMiddleware from "../Middleware/UserAuthorization";
import UserWebhookService from "../Services/UserWebhookService";
import WebhookService from "../Services/WebhookService";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import UserWebhook from "../../Models/DatabaseModels/UserWebhook";
export default class UserWebhookAPI extends BaseAPI {
    constructor() {
        var _a;
        super(UserWebhook, UserWebhookService);
        this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/test`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            var _a, _b, _c, _d, _e;
            try {
                req = req;
                if (!req.body["itemId"]) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid item ID"));
                }
                const item = await this.service.findOneById({
                    id: req.body["itemId"],
                    props: {
                        isRoot: true,
                    },
                    select: {
                        userId: true,
                        projectId: true,
                        webhookUrl: true,
                        secret: true,
                        name: true,
                    },
                });
                if (!item) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Item not found"));
                }
                if (((_a = item.userId) === null || _a === void 0 ? void 0 : _a.toString()) !==
                    ((_c = (_b = req === null || req === void 0 ? void 0 : req.userAuthorization) === null || _b === void 0 ? void 0 : _b.userId) === null || _c === void 0 ? void 0 : _c.toString())) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid user ID"));
                }
                const payload = {
                    eventType: "test",
                    timestamp: new Date().toISOString(),
                    projectId: ((_d = item.projectId) === null || _d === void 0 ? void 0 : _d.toString()) || "",
                    userId: ((_e = item.userId) === null || _e === void 0 ? void 0 : _e.toString()) || "",
                    message: "This is a OneUptime test webhook. Your endpoint is reachable.",
                };
                const sendResult = await this.deliverTestWebhook({
                    url: item.webhookUrl,
                    secret: item.secret || undefined,
                    payload,
                    projectId: item.projectId.toString(),
                    userId: item.userId.toString(),
                });
                return Response.sendJsonObjectResponse(req, res, {
                    ok: sendResult.ok,
                    responseStatusCode: sendResult.statusCode || null,
                    statusMessage: sendResult.message,
                });
            }
            catch (err) {
                return next(err);
            }
        });
    }
    async deliverTestWebhook(input) {
        try {
            const response = (await WebhookService.sendWebhook({
                url: input.url,
                eventType: "test",
                payload: input.payload,
                secret: input.secret,
            }, {
                projectId: new ObjectID(input.projectId),
                userId: new ObjectID(input.userId),
            }));
            if (response &&
                typeof response.isFailure === "function" &&
                response.isFailure()) {
                return {
                    ok: false,
                    statusCode: response.statusCode,
                    message: `Test webhook dispatch failed (status ${response.statusCode}). Check the Webhook Logs for details.`,
                };
            }
            return {
                ok: true,
                statusCode: response === null || response === void 0 ? void 0 : response.statusCode,
                message: "Test webhook dispatched. Check the Webhook Logs and your endpoint for the delivered request.",
            };
        }
        catch (err) {
            const message = err instanceof Error && err.message
                ? err.message
                : "Unknown error sending test webhook.";
            return { ok: false, message };
        }
    }
}
//# sourceMappingURL=UserWebhookAPI.js.map