import { BadGatewayException, Injectable } from '@nestjs/common';
import { Resend } from 'resend';

@Injectable()
export class ResendMailService {
  private readonly resend: Resend;
  private readonly fromEmail: string;

  constructor() {
    const apiKey = process.env.RESEND_API_KEY;
    const fromEmail = process.env.RESEND_FROM_EMAIL;

    if (!apiKey || apiKey.includes('xxxxxxxx')) {
      throw new Error('RESEND_API_KEY is missing or still placeholder in .env');
    }

    if (!fromEmail) {
      throw new Error('RESEND_FROM_EMAIL is missing in .env');
    }

    this.resend = new Resend(apiKey);
    this.fromEmail = fromEmail;
  }

  async sendResetPasswordOtpEmail(email: string, otp: string) {
    const { data, error } = await this.resend.emails.send({
      from: this.fromEmail,
      to: [email],
      subject: 'Your password reset OTP',
      html: `
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <h2>Reset your password</h2>

          <p>You requested to reset your password.</p>
          <p>Use the following one-time code to reset your password:</p>

          <p style="
            font-size: 28px;
            font-weight: bold;
            letter-spacing: 6px;
            background: #f3f4f6;
            padding: 12px 18px;
            border-radius: 8px;
            display: inline-block;
          ">
            ${otp}
          </p>

          <p>This code will expire in 15 minutes.</p>
          <p>If you did not request this, please ignore this email.</p>
        </div>
      `,
    });

    if (error) {
      console.error('Resend email error:', error);

      throw new BadGatewayException({
        message: 'Failed to send reset OTP email',
        resendError: error.message,
      });
    }

    console.log('Reset password OTP email sent:', data);

    return data;
  }

  async sendPasswordChangedEmail(email: string, name?: string | null) {
    const greeting = name ? `Hi ${name},` : 'Hi,';

    const { data, error } = await this.resend.emails.send({
      from: this.fromEmail,
      to: [email],
      subject: 'Your password has been changed',
      html: `
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <h2>Password changed</h2>
          <p>${greeting}</p>
          <p>Your account password was just changed successfully.</p>
          <p>If you did not perform this action, please reset your password immediately and contact support.</p>
        </div>
      `,
    });

    if (error) {
      console.error('Resend email error:', error);

      throw new BadGatewayException({
        message: 'Failed to send password changed email',
        resendError: error.message,
      });
    }

    return data;
  }

  async sendEmailChangeOtpEmail(
    newEmail: string,
    otp: string,
    name?: string | null,
  ) {
    const greeting = name ? `Hi ${name},` : 'Hi,';

    const { data, error } = await this.resend.emails.send({
      from: this.fromEmail,
      to: [newEmail],
      subject: 'Verify your new email address',
      html: `
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <h2>Verify your new email</h2>
          <p>${greeting}</p>
          <p>You requested to change the email on your account to this address.</p>
          <p>Use the following one-time code to confirm the change:</p>

          <p style="
            font-size: 28px;
            font-weight: bold;
            letter-spacing: 6px;
            background: #f3f4f6;
            padding: 12px 18px;
            border-radius: 8px;
            display: inline-block;
          ">
            ${otp}
          </p>

          <p>This code will expire in 15 minutes.</p>
          <p>If you did not request this change, please ignore this email and your current email address will remain unchanged.</p>
        </div>
      `,
    });

    if (error) {
      console.error('Resend email error:', error);

      throw new BadGatewayException({
        message: 'Failed to send email verification OTP',
        resendError: error.message,
      });
    }

    return data;
  }

  async sendEmailChangedNotice(oldEmail: string, newEmail: string) {
    const { data, error } = await this.resend.emails.send({
      from: this.fromEmail,
      to: [oldEmail],
      subject: 'Your account email was changed',
      html: `
        <div style="font-family: Arial, sans-serif; line-height: 1.6;">
          <h2>Email address changed</h2>
          <p>Hi,</p>
          <p>The email address on your account was just changed to <strong>${newEmail}</strong>.</p>
          <p>If you did not perform this action, please contact support immediately.</p>
        </div>
      `,
    });

    if (error) {
      console.error('Resend email error:', error);

      throw new BadGatewayException({
        message: 'Failed to send email-changed notice',
        resendError: error.message,
      });
    }

    return data;
  }
}
