"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OtpverificationController = void 0;
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/naming-convention */
const repository_1 = require("@loopback/repository");
const rest_1 = require("@loopback/rest");
const models_1 = require("../models");
const repositories_1 = require("../repositories");
let OtpverificationController = class OtpverificationController {
    constructor(otpVerificationRepository, buyerRepository, sellerRepository) {
        this.otpVerificationRepository = otpVerificationRepository;
        this.buyerRepository = buyerRepository;
        this.sellerRepository = sellerRepository;
    }
    async createOtp(body) {
        const { phone_number } = body;
        const existingOtp = await this.otpVerificationRepository.findOne({
            where: { mobileNumber: phone_number },
            order: ['createdDate DESC'],
        });
        const now = new Date();
        if (existingOtp && existingOtp.expiresAt) {
            const expiresAt = new Date(existingOtp.expiresAt);
            if (!isNaN(expiresAt.getTime()) && now < expiresAt) {
                const remaining = Math.ceil((expiresAt.getTime() - now.getTime()) / 1000);
                return {
                    success: true,
                    message: `OTP already sent. Please wait ${remaining} seconds before requesting a new one.`,
                    otp: existingOtp.otpCode, // ⚠️ only for console testing
                };
            }
        }
        // Generate new OTP
        const otp = Math.floor(1000 + Math.random() * 9000).toString();
        const expiresAt = new Date(now.getTime() + 2 * 60 * 1000); // 2 minutes
        await this.otpVerificationRepository.create({
            mobileNumber: phone_number,
            otpCode: otp,
            createdDate: now.toISOString(),
            expiresAt: expiresAt.toISOString(),
            lastChanged: now.toISOString(),
        });
        // ✅ Send WhatsApp OTP
        // const sent = await sendOtpWhatsapp(phone_number, otp);
        // if (!sent.success) {
        //   return {
        //     success: false,
        //     message: sent.error ?? 'Failed to send OTP via WhatsApp.',
        //     isWhatsapp: sent.isWhatsapp ?? false,
        //   };
        // }
        return {
            success: true,
            message: 'OTP sent successfully!',
            // message: 'OTP sent successfully via WhatsApp.',
            otp, // ⚠️ return for frontend console log
        };
    }
    // @post('/otp-verifications')
    // async createOtp(
    //   @requestBody({
    //     content: {
    //       'application/json': {
    //         schema: {
    //           type: 'object',
    //           properties: {
    //             phone_number: {type: 'string'},
    //           },
    //           required: ['phone_number'],
    //         },
    //       },
    //     },
    //   })
    //   body: {phone_number: string},
    // ): Promise<object> {
    //   const {phone_number} = body;
    //   const existingOtp = await this.otpVerificationRepository.findOne({
    //     where: {mobileNumber: phone_number},
    //     order: ['createdDate DESC'],
    //   });
    //   const now = new Date();
    //   if (existingOtp && existingOtp.expiresAt) {
    //     const expiresAt = new Date(existingOtp.expiresAt);
    //     if (!isNaN(expiresAt.getTime()) && now < expiresAt) {
    //       const remaining = Math.ceil((expiresAt.getTime() - now.getTime()) / 1000);
    //       return {
    //         success: true,
    //         message: `OTP already sent. Please wait ${remaining} seconds before requesting a new one.`,
    //         otp: existingOtp.otpCode, // For testing/debugging only
    //       };
    //     }
    //   }
    //   // Generate new OTP
    //   const otp = Math.floor(1000 + Math.random() * 9000).toString();
    //   const expiresAt = new Date(now.getTime() + 2 * 60 * 1000); // 2 minutes
    //   await this.otpVerificationRepository.create({
    //     mobileNumber: phone_number,
    //     otpCode: otp,
    //     createdDate: now.toISOString(),
    //     expiresAt: expiresAt.toISOString(),
    //     lastChanged: now.toISOString(),
    //   });
    //   Send WhatsApp OTP
    //   const sent = await sendOtpWhatsapp(phone_number, otp);
    //   if (!sent.success) {
    //     return {
    //       success: false,
    //       message: sent.error ? sent.error : 'Failed to send OTP via WhatsApp.',
    //       isWhatsapp: sent.isWhatsapp ?? false,
    //     };
    //   }
    //   return {
    //     success: true,
    //     message: 'OTP sent successfully!',
    //     // message: 'OTP sent successfully via WhatsApp.',
    //     otp, // For frontend console log
    //     // isWhatsapp: sent.isWhatsapp,
    //   };
    // }
    async verifyOtp(body) {
        const { phone_number, otp } = body;
        const existing = await this.otpVerificationRepository.findOne({
            where: {
                mobileNumber: phone_number,
                otpCode: otp,
            },
            order: ['created_date DESC'],
        });
        if (!existing) {
            return {
                success: false,
                message: 'Invalid OTP or phone number.',
            };
        }
        // ✅ Safely check if `expires_at` exists
        if (!existing.expiresAt) {
            return {
                success: false,
                message: 'Expiry time not found for this OTP.',
            };
        }
        const expiresAt = new Date(existing.expiresAt);
        const now = new Date();
        // ✅ Validate if `expiresAt` is a valid date
        if (isNaN(expiresAt.getTime())) {
            return {
                success: false,
                message: 'Invalid expiry date format.',
            };
        }
        if (now > expiresAt) {
            return {
                success: false,
                message: 'OTP has expired.',
            };
        }
        // ✅ Optionally mark the OTP as used (optional step)
        // await this.otpVerificationRepository.updateById(existing.id, {is_used: true});
        return {
            success: true,
            message: 'OTP verified successfully.',
        };
    }
    async checkUser(body) {
        const { phone_number } = body;
        console.log('Checking user for phone:', phone_number);
        // Check seller table
        const seller = await this.sellerRepository.findOne({
            where: { sellerMobile: phone_number.trim() },
        });
        console.log(seller);
        if (seller) {
            return { source: 'seller', data: seller };
        }
        // Check buyer table
        const buyer = await this.buyerRepository.findOne({
            where: { buyerMobile: phone_number.trim() },
        });
        console.log(buyer);
        if (buyer) {
            return { source: 'buyer', data: buyer };
        }
        // No match
        return { source: 'none', data: null };
    }
    async find(filter) {
        return this.otpVerificationRepository.find(filter);
    }
    async updateAll(otpVerification, where) {
        return this.otpVerificationRepository.updateAll(otpVerification, where);
    }
    async findById(id, filter) {
        return this.otpVerificationRepository.findById(id, filter);
    }
    async updateById(id, otpVerification) {
        await this.otpVerificationRepository.updateById(id, otpVerification);
    }
    async replaceById(id, otpVerification) {
        await this.otpVerificationRepository.replaceById(id, otpVerification);
    }
    async deleteById(id) {
        await this.otpVerificationRepository.deleteById(id);
    }
};
exports.OtpverificationController = OtpverificationController;
tslib_1.__decorate([
    (0, rest_1.post)('/otp-verifications'),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: {
                    type: 'object',
                    properties: {
                        phone_number: { type: 'string' },
                    },
                    required: ['phone_number'],
                },
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "createOtp", null);
tslib_1.__decorate([
    (0, rest_1.post)('/otp-verifications/verify'),
    (0, rest_1.response)(200, {
        description: 'Verify OTP for given phone number',
        content: { 'application/json': { schema: { type: 'object' } } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: {
                    type: 'object',
                    properties: {
                        phone_number: { type: 'string' },
                        otp: { type: 'string' },
                    },
                    required: ['phone_number', 'otp'],
                },
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "verifyOtp", null);
tslib_1.__decorate([
    (0, rest_1.post)('/otp-verifications/check-user'),
    (0, rest_1.response)(200, {
        description: 'Check if phone exists in Buyer or Seller',
        content: {
            'application/json': {
                schema: {
                    type: 'object',
                    properties: {
                        source: { type: 'string' },
                        data: { type: 'object' },
                    },
                },
            },
        },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: {
                    type: 'object',
                    properties: {
                        phone_number: { type: 'string' },
                    },
                    required: ['phone_number'],
                },
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "checkUser", null);
tslib_1.__decorate([
    (0, rest_1.get)('/otp-verifications'),
    (0, rest_1.response)(200, {
        description: 'Array of OtpVerification model instances',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.OtpVerification, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.OtpVerification)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/otp-verifications'),
    (0, rest_1.response)(200, {
        description: 'OtpVerification PATCH success count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.OtpVerification, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.OtpVerification)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.OtpVerification, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.get)('/otp-verifications/{id}'),
    (0, rest_1.response)(200, {
        description: 'OtpVerification model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.OtpVerification, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.OtpVerification, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/otp-verifications/{id}'),
    (0, rest_1.response)(204, {
        description: 'OtpVerification PATCH success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.OtpVerification, { partial: true }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.OtpVerification]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.put)('/otp-verifications/{id}'),
    (0, rest_1.response)(204, {
        description: 'OtpVerification PUT success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, (0, rest_1.requestBody)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.OtpVerification]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/otp-verifications/{id}'),
    (0, rest_1.response)(204, {
        description: 'OtpVerification DELETE success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number]),
    tslib_1.__metadata("design:returntype", Promise)
], OtpverificationController.prototype, "deleteById", null);
exports.OtpverificationController = OtpverificationController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.OtpVerificationRepository)),
    tslib_1.__param(1, (0, repository_1.repository)(repositories_1.BuyerMasterRepository)),
    tslib_1.__param(2, (0, repository_1.repository)(repositories_1.SellerMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.OtpVerificationRepository,
        repositories_1.BuyerMasterRepository,
        repositories_1.SellerMasterRepository])
], OtpverificationController);
//# sourceMappingURL=otpverification.controller.js.map