import UserMiddleware from "../Middleware/UserAuthorization";
import UserWhatsAppService from "../Services/UserWhatsAppService";
import UserNotificationRuleService from "../Services/UserNotificationRuleService";
import Response from "../Utils/Response";
import logger, { getLogAttributesFromRequest } from "../Utils/Logger";
import BaseAPI from "./BaseAPI";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import UserWhatsApp from "../../Models/DatabaseModels/UserWhatsApp";
export default class UserWhatsAppAPI extends BaseAPI {
    constructor() {
        var _a, _b;
        super(UserWhatsApp, UserWhatsAppService);
        this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/verify`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            var _a, _b, _c;
            try {
                req = req;
                if (!req.body.itemId) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid item ID"));
                }
                if (!req.body.code) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid code"));
                }
                const item = await this.service.findOneById({
                    id: req.body["itemId"],
                    props: {
                        isRoot: true,
                    },
                    select: {
                        userId: true,
                        projectId: true,
                        verificationCode: true,
                        isVerified: true,
                    },
                });
                if (!item) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Item not found"));
                }
                if (item.isVerified) {
                    return Response.sendErrorResponse(req, res, new BadDataException("WhatsApp number already verified"));
                }
                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"));
                }
                if (item.verificationCode !== req.body["code"]) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid code"));
                }
                await this.service.updateOneById({
                    id: item.id,
                    props: {
                        isRoot: true,
                    },
                    data: {
                        isVerified: true,
                    },
                });
                // Create default notification rules for this verified WhatsApp number
                try {
                    await UserNotificationRuleService.addDefaultNotificationRulesForVerifiedMethod({
                        projectId: new ObjectID(item.projectId.toString()),
                        userId: new ObjectID(item.userId.toString()),
                        notificationMethod: {
                            userWhatsAppId: item.id,
                        },
                    });
                }
                catch (e) {
                    logger.error(e, getLogAttributesFromRequest(req));
                }
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (err) {
                return next(err);
            }
        });
        this.router.post(`${(_b = new this.entityType()
            .getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/resend-verification-code`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            var _a, _b, _c;
            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,
                    },
                });
                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"));
                }
                await this.service.resendVerificationCode(req.body.itemId);
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (err) {
                return next(err);
            }
        });
    }
}
//# sourceMappingURL=UserWhatsAppAPI.js.map