"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 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) {
        this.orderRepo = orderRepo;
        this.userRepo = userRepo;
        this.vendorRepo = vendorRepo;
        this.vendorPlanRepo = vendorPlanRepo;
    }
    async success(query, res) {
        const ref = query.OrderRef;
        const status = query.STATUS;
        if (!ref || status !== '9') {
            return res.status(200).json({
                success: false,
                message: 'Payment failed or invalid reference',
            });
        }
        let verify;
        try {
            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 },
            });
        }
        catch (err) {
            console.error('TELR VERIFY ERROR:', err?.response?.data || err.message);
            return res.status(200).json({
                success: false,
                message: 'Unable to verify payment',
            });
        }
        if (verify?.data?.order?.status?.code !== 3) {
            return res.status(200).json({
                success: false,
                message: 'Payment not approved',
            });
        }
        try {
            const order = await this.orderRepo.findOne({
                where: { telrRef: ref },
            });
            if (order && order.paymentStatus !== 'PAID') {
                order.paymentStatus = 'PAID';
                await this.orderRepo.save(order);
                await this.vendorRepo.save({
                    planId: order.planId,
                    user: { id: order.userId },
                });
                await this.vendorPlanRepo.save({
                    vendorId: order.userId,
                    planId: order.planId,
                    status: status_enum_1.Status.INACTIVE,
                    start_date: new Date(),
                });
                await this.userRepo.update(order.userId, {
                    roles: [user_entity_1.UserRole.VENDOR],
                });
            }
        }
        catch (dbErr) {
            console.error('ORDER PROCESS ERROR:', dbErr);
        }
        return res.status(200).json({
            success: true,
            message: 'Payment successful',
            orderRef: ref,
        });
    }
    cancel(res) {
        return res.status(200).json({
            success: false,
            status: 'CANCELLED',
        });
    }
    decline(res) {
        return res.status(200).json({
            success: false,
            status: 'DECLINED',
        });
    }
};
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);
__decorate([
    (0, common_1.Get)('cancel'),
    __param(0, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], TelrVendorController.prototype, "cancel", null);
__decorate([
    (0, common_1.Get)('decline'),
    __param(0, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], TelrVendorController.prototype, "decline", 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])
], TelrVendorController);
//# sourceMappingURL=telr_vendor.controller.js.map