"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 MailService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MailService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const nodemailer = require("nodemailer");
let MailService = MailService_1 = class MailService {
    constructor(config) {
        this.config = config;
        this.logger = new common_1.Logger(MailService_1.name);
        this.transporter = null;
        this.enabled = false;
    }
    onModuleInit() {
        const host = this.config.get('mail.host', '');
        const user = this.config.get('mail.user', '');
        const pass = this.config.get('mail.pass', '');
        if (!host || !user || !pass) {
            this.logger.warn('SMTP not configured — emails will be logged to console only');
            return;
        }
        const port = this.config.get('mail.port', 587);
        const secure = this.config.get('mail.secure', port === 465);
        this.transporter = nodemailer.createTransport({
            host,
            port,
            secure,
            auth: { user, pass },
        });
        this.enabled = true;
        this.logger.log(`SMTP connected (${host}:${port})`);
    }
    async sendMail(options) {
        const from = this.config.get('mail.from', 'Divyourday <noreply@divyourday.app>');
        if (!this.enabled || !this.transporter) {
            this.logger.warn(`[DEV] Email to ${options.to}: ${options.subject}\n${options.text}`);
            return false;
        }
        try {
            await this.transporter.sendMail({
                from,
                to: options.to,
                subject: options.subject,
                text: options.text,
                html: options.html,
            });
            this.logger.log(`Email sent to ${options.to}: ${options.subject}`);
            return true;
        }
        catch (err) {
            this.logger.error(`Failed to send email to ${options.to}: ${String(err)}`);
            this.logger.warn(`[FALLBACK] ${options.text}`);
            return false;
        }
    }
    async sendGroupInvite(params) {
        const expires = params.expiresAt.toLocaleDateString(undefined, {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
        const subject = `${params.invitedByName} invited you to join “${params.groupName}” on Divyourday`;
        const text = [
            `${params.invitedByName} invited you to join the group “${params.groupName}” on Divyourday.`,
            '',
            'Divyourday helps you split expenses with friends and settle up fairly.',
            '',
            `Join here: ${params.inviteUrl}`,
            '',
            `This invite expires on ${expires}.`,
            '',
            'If you didn’t expect this email, you can ignore it.',
        ].join('\n');
        const html = `
<!DOCTYPE html>
<html>
<body style="margin:0;padding:0;background:#f4f7f6;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="padding:32px 16px;">
    <tr>
      <td align="center">
        <table width="100%" style="max-width:480px;background:#ffffff;border-radius:16px;overflow:hidden;border:1px solid #e2e8e6;">
          <tr>
            <td style="background:#0F6B5C;padding:24px 28px;">
              <p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:-0.02em;">Divyourday</p>
            </td>
          </tr>
          <tr>
            <td style="padding:28px;">
              <h1 style="margin:0 0 12px;font-size:20px;color:#0f172a;font-weight:600;">You're invited</h1>
              <p style="margin:0 0 16px;font-size:15px;line-height:1.5;color:#475569;">
                <strong>${escapeHtml(params.invitedByName)}</strong> invited you to join
                <strong>${escapeHtml(params.groupName)}</strong> on Divyourday — split expenses and settle up together.
              </p>
              <p style="margin:0 0 24px;">
                <a href="${params.inviteUrl}"
                   style="display:inline-block;background:#0F6B5C;color:#ffffff;text-decoration:none;padding:12px 22px;border-radius:10px;font-size:15px;font-weight:600;">
                  Join the group
                </a>
              </p>
              <p style="margin:0 0 8px;font-size:13px;color:#64748b;line-height:1.5;">
                Or copy this link:<br/>
                <a href="${params.inviteUrl}" style="color:#0F6B5C;word-break:break-all;">${params.inviteUrl}</a>
              </p>
              <p style="margin:16px 0 0;font-size:12px;color:#94a3b8;">
                This invite expires on ${expires}. If you didn’t expect this, ignore this email.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`.trim();
        return this.sendMail({ to: params.to, subject, html, text });
    }
    async sendPasswordReset(params) {
        const subject = 'Reset your Divyourday password';
        const text = [
            `Hi ${params.name},`,
            '',
            'We received a request to reset your Divyourday password.',
            '',
            `Reset your password: ${params.resetUrl}`,
            '',
            'This link expires in 1 hour. If you didn’t request a reset, you can ignore this email.',
        ].join('\n');
        const html = emailShell({
            title: 'Reset your password',
            bodyHtml: `
        <p style="margin:0 0 16px;font-size:15px;line-height:1.5;color:#475569;">
          Hi <strong>${escapeHtml(params.name)}</strong>, we received a request to reset your Divyourday password.
        </p>
        <p style="margin:0 0 24px;">
          <a href="${params.resetUrl}"
             style="display:inline-block;background:#0F6B5C;color:#ffffff;text-decoration:none;padding:12px 22px;border-radius:10px;font-size:15px;font-weight:600;">
            Reset password
          </a>
        </p>
        <p style="margin:0 0 8px;font-size:13px;color:#64748b;line-height:1.5;">
          Or copy this link:<br/>
          <a href="${params.resetUrl}" style="color:#0F6B5C;word-break:break-all;">${params.resetUrl}</a>
        </p>
        <p style="margin:16px 0 0;font-size:12px;color:#94a3b8;">
          This link expires in 1 hour. If you didn’t request this, ignore this email.
        </p>
      `,
        });
        return this.sendMail({ to: params.to, subject, html, text });
    }
    async sendEmailVerification(params) {
        const subject = 'Verify your Divyourday email';
        const text = [
            `Hi ${params.name},`,
            '',
            'Thanks for signing up for Divyourday. Please verify your email to activate your account.',
            '',
            `Verify email: ${params.verifyUrl}`,
            '',
            'This link expires in 24 hours. If you didn’t create an account, you can ignore this email.',
        ].join('\n');
        const html = emailShell({
            title: 'Verify your email',
            bodyHtml: `
        <p style="margin:0 0 16px;font-size:15px;line-height:1.5;color:#475569;">
          Hi <strong>${escapeHtml(params.name)}</strong>, thanks for signing up for Divyourday.
          Please verify your email to activate your account.
        </p>
        <p style="margin:0 0 24px;">
          <a href="${params.verifyUrl}"
             style="display:inline-block;background:#0F6B5C;color:#ffffff;text-decoration:none;padding:12px 22px;border-radius:10px;font-size:15px;font-weight:600;">
            Verify email
          </a>
        </p>
        <p style="margin:0 0 8px;font-size:13px;color:#64748b;line-height:1.5;">
          Or copy this link:<br/>
          <a href="${params.verifyUrl}" style="color:#0F6B5C;word-break:break-all;">${params.verifyUrl}</a>
        </p>
        <p style="margin:16px 0 0;font-size:12px;color:#94a3b8;">
          This link expires in 24 hours. If you didn’t create an account, ignore this email.
        </p>
      `,
        });
        return this.sendMail({ to: params.to, subject, html, text });
    }
};
exports.MailService = MailService;
exports.MailService = MailService = MailService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService])
], MailService);
function emailShell(params) {
    return `
<!DOCTYPE html>
<html>
<body style="margin:0;padding:0;background:#f4f7f6;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="padding:32px 16px;">
    <tr>
      <td align="center">
        <table width="100%" style="max-width:480px;background:#ffffff;border-radius:16px;overflow:hidden;border:1px solid #e2e8e6;">
          <tr>
            <td style="background:#0F6B5C;padding:24px 28px;">
              <p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:-0.02em;">Divyourday</p>
            </td>
          </tr>
          <tr>
            <td style="padding:28px;">
              <h1 style="margin:0 0 12px;font-size:20px;color:#0f172a;font-weight:600;">${escapeHtml(params.title)}</h1>
              ${params.bodyHtml}
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`.trim();
}
function escapeHtml(value) {
    return value
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}
//# sourceMappingURL=mail.service.js.map