"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.TelrVendorController = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const axios_1 = require("axios");
const user_entity_1 = require("../user/user.entity");
const user_services_1 = require("../user/user.services");
const firebase_service_1 = require("../fcm/firebase.service");
const vendor_plan_order_entity_1 = require("../../common/vendor/vendor_plan_order.entity");
const vendor_entity_1 = require("../../common/vendor/vendor.entity");
const vendor_plan_entity_1 = require("../../common/vendor/vendor_plan.entity");
const status_enum_1 = require("../../common/columntype/status.enum");
let TelrVendorController = class TelrVendorController {
    constructor(orderRepo, userRepo, vendorRepo, vendorPlanRepo, userService, firebaseService) {
        this.orderRepo = orderRepo;
        this.userRepo = userRepo;
        this.vendorRepo = vendorRepo;
        this.vendorPlanRepo = vendorPlanRepo;
        this.userService = userService;
        this.firebaseService = firebaseService;
    }
    async success(query, res) {
        console.log('TELR SUCCESS QUERY:', query);
        const ref = query.OrderRef;
        if (!ref) {
            return res.redirect('https://cars247.ae/cars24x7admin/payment/failed');
        }
        const verify = await axios_1.default.post(process.env.TELR_BASE_URL, {
            method: 'check',
            store: process.env.TELR_STORE_ID,
            authkey: process.env.TELR_AUTH_KEY,
            order: { ref },
        });
        if (verify.data.order.status.code !== 3) {
            return res.redirect('https://cars247.ae/cars24x7admin/payment/failed');
        }
        const order = await this.orderRepo.findOne({ where: { telrRef: ref } });
        if (!order || order.paymentStatus === 'PAID') {
            return res.redirect('https://cars247.ae/cars24x7admin/payment/success');
        }
        order.paymentStatus = 'PAID';
        await this.orderRepo.save(order);
        const vendor = this.vendorRepo.create({
            planId: order.planId,
            user: { id: order.userId },
        });
        await this.vendorRepo.save(vendor);
        const vendorPlan = this.vendorPlanRepo.create({
            vendorId: order.userId,
            planId: order.planId,
            status: status_enum_1.Status.ACTIVE,
            start_date: new Date(),
        });
        await this.vendorPlanRepo.save(vendorPlan);
        const user = await this.userRepo.findOne({ where: { id: order.userId } });
        user.roles = [user_entity_1.UserRole.VENDOR];
        await this.userRepo.save(user);
        const admins = await this.userService.findAdmin();
        const tokens = admins
            .map(a => a.deviceId)
            .filter(t => t && t !== 'null' && t !== 'undefined');
        for (const token of tokens) {
            try {
                await this.firebaseService.sendNotification(token, 'New Vendor Subscription 🚀', 'Payment successful. A new vendor has been activated.', 'vendorplan');
            }
            catch (fcmError) {
                console.error(`FCM notification failed for admin token ${token}:`, fcmError?.message ?? fcmError);
            }
        }
        return res.redirect('https://cars247.ae/cars24x7admin/payment/success');
    }
};
exports.TelrVendorController = TelrVendorController;
__decorate([
    (0, common_1.Get)('success'),
    __param(0, (0, common_1.Query)()),
    __param(1, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], TelrVendorController.prototype, "success", null);
exports.TelrVendorController = TelrVendorController = __decorate([
    (0, common_1.Controller)('telr/vendor'),
    __param(0, (0, typeorm_1.InjectRepository)(vendor_plan_order_entity_1.VendorPlanOrder)),
    __param(1, (0, typeorm_1.InjectRepository)(user_entity_1.User)),
    __param(2, (0, typeorm_1.InjectRepository)(vendor_entity_1.Vendor)),
    __param(3, (0, typeorm_1.InjectRepository)(vendor_plan_entity_1.VendorPlan)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        user_services_1.UserService,
        firebase_service_1.FirebaseService])
], TelrVendorController);
//# sourceMappingURL=telr_vendor.controller_old.js.map