"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.VendorPlanService = 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 otp_email_service_1 = require("../emailotp/otp-email.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 VendorPlanService = class VendorPlanService {
    constructor(userRepo, orderRepo, vendorRepo, vendorPlanRepo, emailOtpService) {
        this.userRepo = userRepo;
        this.orderRepo = orderRepo;
        this.vendorRepo = vendorRepo;
        this.vendorPlanRepo = vendorPlanRepo;
        this.emailOtpService = emailOtpService;
    }
    async create(dto) {
        return this.userRepo.manager.transaction(async (manager) => {
            const user = await manager.findOne(user_entity_1.User, { where: { id: Number(dto.userId) } });
            if (!user)
                throw new common_1.NotFoundException('User not found');
            const order = manager.create(vendor_plan_order_entity_1.VendorPlanOrder, {
                userId: Number(dto.userId),
                planId: Number(dto.planId),
                price: Number(dto.price),
                paymentStatus: 'PENDING',
            });
            const savedOrder = await manager.save(order);
            const bypassTelr = process.env.BYPASS_TELR_PAYMENT === 'true';
            let paymentUrl;
            if (bypassTelr) {
                savedOrder.telrRef = `BYPASS-${savedOrder.id}`;
                savedOrder.paymentStatus = 'PAID';
                await manager.save(savedOrder);
                await manager.save(vendor_entity_1.Vendor, {
                    planId: savedOrder.planId,
                    user: { id: savedOrder.userId },
                });
                await manager.save(vendor_plan_entity_1.VendorPlan, {
                    vendorId: savedOrder.userId,
                    planId: savedOrder.planId,
                    status: status_enum_1.Status.ACTIVE,
                    start_date: new Date(),
                });
                user.roles = [user_entity_1.UserRole.VENDOR];
                await manager.save(user);
                paymentUrl = `https://cars247.ae/cars24x7admin/payment/success`;
            }
            else {
                const telrRes = await axios_1.default.post(process.env.TELR_BASE_URL, {
                    method: 'create',
                    store: Number(process.env.TELR_STORE_ID),
                    authkey: process.env.TELR_AUTH_KEY,
                    order: {
                        cartid: `VENDOR-${savedOrder.id}`,
                        test: 1,
                        amount: Number(dto.price),
                        currency: 'AED',
                        description: `Vendor plan payment - Order #${savedOrder.id}`,
                    },
                    return: {
                        authorised: ' https://cars247.ae/telr/vendor/success',
                        cancelled: 'https://cars247.ae/telr/vendor/cancel',
                        declined: 'https://cars247.ae/telr/vendor/decline',
                    },
                }, { headers: { 'Content-Type': 'application/json' } });
                if (!telrRes.data?.order?.ref) {
                    throw new Error(`Telr payment creation failed: ${JSON.stringify(telrRes.data)}`);
                }
                savedOrder.telrRef = telrRes.data.order.ref;
                await manager.save(savedOrder);
                paymentUrl = telrRes.data.order.url;
            }
            const resetLink = `https://cars247.ae/cars24x7admin/authentication/sign-in`;
            await this.emailOtpService.sendMakeVendorEmail(user.email, resetLink);
            return {
                paymentUrl,
                orderId: savedOrder.id,
            };
        });
    }
};
exports.VendorPlanService = VendorPlanService;
exports.VendorPlanService = VendorPlanService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.User)),
    __param(1, (0, typeorm_1.InjectRepository)(vendor_plan_order_entity_1.VendorPlanOrder)),
    __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,
        otp_email_service_1.emailOtpService])
], VendorPlanService);
//# sourceMappingURL=vendor_plan.service.js.map