"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotificationService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const nodemailer = __importStar(require("nodemailer"));
let NotificationService = class NotificationService {
    config;
    transporter = null;
    twilioClient = null;
    fromEmail;
    twilioFrom;
    isProd;
    debug;
    constructor(config) {
        this.config = config;
        this.isProd = (process.env.NODE_ENV || '').toLowerCase() === 'production';
        this.debug = (process.env.NOTIFY_DEBUG || '').toLowerCase() === 'true';
        const host = this.config.get('SMTP_HOST');
        const port = Number(this.config.get('SMTP_PORT') || 587);
        const user = this.config.get('SMTP_USER');
        const pass = this.config.get('SMTP_PASS');
        this.fromEmail = this.config.get('SMTP_FROM') || 'no-reply@example.com';
        if (host && user && pass) {
            this.transporter = nodemailer.createTransport({
                host,
                port,
                secure: port === 465,
                auth: { user, pass },
            });
            void this.transporter.verify().then(() => this.debug && console.log('[Mailer] Transport verified'), (err) => console.error('[Mailer] Transport verification failed:', err?.message || err));
        }
        else if (this.isProd) {
            console.warn('[Mailer] Missing SMTP configuration in production.');
        }
        const sid = this.config.get('TWILIO_SID');
        const token = this.config.get('TWILIO_TOKEN');
        this.twilioFrom = this.config.get('TWILIO_FROM');
        if (sid && token) {
            try {
                const { Twilio } = require('twilio');
                this.twilioClient = new Twilio(sid, token);
            }
            catch {
                console.error('[Twilio] SDK not available. Install "twilio" to enable SMS.');
            }
        }
        else if (this.isProd) {
            console.warn('[Twilio] Missing SID/TOKEN in production.');
        }
    }
    async sendOtp(channel, to, code, expiresInMinutes) {
        if (channel === 'email') {
            return this.sendOtpEmail(to, code, expiresInMinutes);
        }
        return this.sendOtpSms(to, code, expiresInMinutes);
    }
    async sendOtpEmail(to, code, expiresInMinutes) {
        const subject = 'Your password reset code';
        const html = `
      <div style="font-family:Arial,Helvetica,sans-serif;line-height:1.5">
        <h2>Password reset</h2>
        <p>Use the following one-time code to reset your password:</p>
        <p style="font-size:22px;font-weight:bold;letter-spacing:2px">${code}</p>
        <p>This code expires in <strong>${expiresInMinutes} minutes</strong>.</p>
        <p>If you did not request this, you can ignore this message.</p>
      </div>
    `;
        const text = `Password reset code: ${code}\n` +
            `This code expires in ${expiresInMinutes} minutes.\n` +
            `If you did not request this, you can ignore this message.`;
        if (this.transporter) {
            try {
                await this.transporter.sendMail({ from: this.fromEmail, to, subject, html, text });
                this.debug && console.log(`[Mailer] OTP email sent to=${to}`);
                return { ok: true };
            }
            catch (err) {
                if (!this.isProd) {
                    console.error('[Mailer] send error:', err);
                    console.log(`DEV OTP EMAIL to=${to} code=${code}`);
                    return { ok: true, dev: true };
                }
                throw new common_1.InternalServerErrorException('Failed to send email.');
            }
        }
        if (!this.isProd) {
            console.log(`DEV OTP EMAIL to=${to} code=${code}`);
            return { ok: true, dev: true };
        }
        throw new common_1.InternalServerErrorException('Email provider not configured.');
    }
    async sendOtpSms(to, code, expiresInMinutes) {
        const body = `Your password reset code is ${code}. It expires in ${expiresInMinutes} minutes.`;
        if (this.twilioClient && this.twilioFrom) {
            try {
                await this.twilioClient.messages.create({ body, from: this.twilioFrom, to });
                this.debug && console.log(`[Twilio] OTP SMS sent to=${to}`);
                return { ok: true };
            }
            catch (err) {
                if (!this.isProd) {
                    console.error('[Twilio] send error:', err);
                    console.log(`DEV OTP SMS to=${to} code=${code}`);
                    return { ok: true, dev: true };
                }
                throw new common_1.InternalServerErrorException('Failed to send SMS.');
            }
        }
        if (!this.isProd) {
            console.log(`DEV OTP SMS to=${to} code=${code}`);
            return { ok: true, dev: true };
        }
        throw new common_1.InternalServerErrorException('SMS provider not configured.');
    }
};
exports.NotificationService = NotificationService;
exports.NotificationService = NotificationService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService])
], NotificationService);
//# sourceMappingURL=notification.service.js.map