import { Injectable, Logger } from '@nestjs/common';
import * as nodemailer from 'nodemailer';

/** Escapes user-supplied values (names, organization names) before they go into email HTML. */
function escapeHtml(value: string): string {
  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}

export interface SendMailOptions {
  to: string;
  subject: string;
  html: string;
  text: string;
}

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private transporter: nodemailer.Transporter | null = null;

  constructor() {
    const host = process.env.SMTP_HOST;
    const port = Number(process.env.SMTP_PORT);
    const user = process.env.SMTP_USER;
    const pass = process.env.SMTP_PASS;

    if (host && user && pass) {
      this.transporter = nodemailer.createTransport({
        host,
        port,
        secure: port === 465,
        auth: { user, pass },
      });
    } else {
      this.logger.log('SMTP not fully configured; transactional emails will be logged to console in dev/test mode.');
    }
  }

  // Transmits email via SMTP transporter or falls back to logger in dev/test mode.
  async sendMail(options: SendMailOptions): Promise<{ success: boolean; mocked: boolean }> {
    const from = process.env.SMTP_FROM;

    if (!this.transporter || process.env.NODE_ENV === 'test') {
      this.logger.log(process.env.NODE_ENV === 'production' ? `[EMAIL NOT SENT - SMTP not configured] To ${options.to}: "${options.subject}"` : `[MOCK EMAIL TO ${options.to}] Subject: "${options.subject}"\nBody: ${options.text}`);
      return { success: false, mocked: true };
    }

    try {
      const info = await this.transporter.sendMail({
        from,
        to: options.to,
        subject: options.subject,
        text: options.text,
        html: options.html,
      });
      this.logger.log(`Email "${options.subject}" accepted by SMTP for ${options.to} (${info.messageId})`);
      return { success: true, mocked: false };
    } catch (err) {
      this.logger.error(`Failed to send email to ${options.to}: ${(err as Error).message}`);
      return { success: false, mocked: false };
    }
  }

  // Sends a password reset email with a single-use token URL.
  async sendPasswordResetEmail(to: string, rawResetLink: string) {
    const resetLink = escapeHtml(rawResetLink);
    const subject = 'Reset Your TechCMantix CRM Password';
    const text = `You requested a password reset. Click the link below (valid for 1 hour):\n\n${rawResetLink}\n\nIf you did not request this, please ignore this email.`;
    const html = `
      <div style="font-family: sans-serif; max-width: 560px; margin: 0 auto; padding: 24px;">
        <h2 style="color: #0E7C66;">Reset your password</h2>
        <p>You recently requested to reset your password for TechCMantix CRM. Click the button below to set a new password. This link is valid for 1 hour and can only be used once.</p>
        <p style="margin: 24px 0;">
          <a href="${resetLink}" style="background-color: #0E7C66; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 8px; display: inline-block; font-weight: bold;">
            Reset Password
          </a>
        </p>
        <p style="color: #64748B; font-size: 13px;">Or copy and paste this URL into your browser:<br/><a href="${resetLink}">${resetLink}</a></p>
        <p style="color: #94A3B8; font-size: 12px; margin-top: 32px;">If you did not request a password reset, you can safely ignore this email.</p>
      </div>
    `;
    return this.sendMail({ to, subject, text, html });
  }

  // Sends an invitation email with an onboarding URL to a new member.
  async sendInvitationEmail(to: string, rawName: string, rawOrgName: string, rawInviteLink: string) {
    const subject = `You've been invited to join ${rawOrgName.replace(/[\r\n]+/g, ' ')} on TechCMantix CRM`;
    const text = `Hello ${rawName},\n\nYou have been invited to join ${rawOrgName} on TechCMantix CRM.\n\nClick the link below to accept your invitation and create your password (valid for 7 days):\n${rawInviteLink}\n\nWelcome aboard!`;
    const name = escapeHtml(rawName);
    const orgName = escapeHtml(rawOrgName);
    const inviteLink = escapeHtml(rawInviteLink);
    const html = `
      <div style="font-family: sans-serif; max-width: 560px; margin: 0 auto; padding: 24px;">
        <h2 style="color: #0E7C66;">Welcome to TechCMantix CRM</h2>
        <p>Hello <strong>${name}</strong>,</p>
        <p>You have been invited to join <strong>${orgName}</strong> on TechCMantix CRM.</p>
        <p style="margin: 24px 0;">
          <a href="${inviteLink}" style="background-color: #0E7C66; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 8px; display: inline-block; font-weight: bold;">
            Accept Invitation
          </a>
        </p>
        <p style="color: #64748B; font-size: 13px;">Or copy and paste this URL into your browser:<br/><a href="${inviteLink}">${inviteLink}</a></p>
      </div>
    `;
    return this.sendMail({ to, subject, text, html });
  }
}
