import { env } from '../config/env';
import { AppError } from '../utils/AppError';
import { createPlatformMailSender, isPlatformMailConfigured } from './mail/MailSender';

export class AuthMailService {
  private assertConfigured() {
    if (!isPlatformMailConfigured()) {
      throw new AppError(
        'service_unavailable',
        503,
        'Email delivery is not configured. Contact support or use Google/LinkedIn sign-in.',
      );
    }
  }

  private fromAddress(): string {
    if (env.MAIL_TRANSPORT === 'gmail_api' && env.GMAIL_USER) {
      return env.GMAIL_USER;
    }
    return env.EMAIL_FROM;
  }

  private async sendOrThrow(options: {
    to: string;
    subject: string;
    html: string;
  }): Promise<void> {
    try {
      await createPlatformMailSender().send({
        from: this.fromAddress(),
        ...options,
      });
    } catch (err) {
      if (err instanceof AppError) throw err;
      throw new AppError(
        'service_unavailable',
        503,
        'We could not send email right now. Please try again in a few minutes or use Google/LinkedIn sign-in.',
      );
    }
  }

  async sendWelcomePassword(
    email: string,
    fullName: string,
    password: string,
  ): Promise<void> {
    this.assertConfigured();
    await this.sendOrThrow({
      to: email,
      subject: 'Your Calendar account password',
      html: `
        <p>Hi ${fullName},</p>
        <p>Your account has been created. Sign in with this temporary password:</p>
        <p><strong style="font-family:monospace;font-size:1.1em">${password}</strong></p>
        <p>For your security, you will be asked to choose a new password after signing in.</p>
        <p><a href="${env.APP_URL}/login">Sign in</a></p>
      `,
    });
  }

  async sendPasswordResetLink(
    email: string,
    fullName: string,
    resetUrl: string,
  ): Promise<void> {
    this.assertConfigured();
    await this.sendOrThrow({
      to: email,
      subject: 'Reset your Calendar password',
      html: `
        <p>Hi ${fullName},</p>
        <p>We received a request to reset your password. Click the link below (valid for 1 hour):</p>
        <p><a href="${resetUrl}">Reset password</a></p>
        <p>If you did not request this, you can ignore this email.</p>
      `,
    });
  }

  async sendPasswordChangedNotification(email: string, fullName: string): Promise<void> {
    if (!isPlatformMailConfigured()) return;
    try {
      await createPlatformMailSender().send({
        from: this.fromAddress(),
        to: email,
        subject: 'Your Calendar password was changed',
        html: `
          <p>Hi ${fullName},</p>
          <p>Your account password was changed successfully.</p>
          <p>If you did not make this change, contact support immediately and reset your password.</p>
        `,
      });
    } catch {
      // Password is already updated; do not fail the request if the notice email fails.
    }
  }
}
