import { render } from '@react-email/render';
import nodemailer from 'nodemailer';
import { SigningRequestEmail } from '@/emails/SigningRequestEmail';
import React from 'react';

function createTransporter() {
  return nodemailer.createTransport({
    host: process.env.CONTACT_SMTP_HOST!,
    port: Number(process.env.CONTACT_SMTP_PORT ?? 465),
    secure: Number(process.env.CONTACT_SMTP_PORT ?? 465) === 465,
    auth: {
      user: process.env.CONTACT_EMAIL_USER!,
      pass: process.env.CONTACT_EMAIL_PASS!,
    },
  });
}

export async function sendSigningRequestEmail(opts: {
  to: string;
  clientName?: string;
  documentName: string;
  signingUrl: string;
  expiresAt: Date;
}): Promise<void> {
  const expiryDate = opts.expiresAt.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });
  const html = await render(
    React.createElement(SigningRequestEmail, {
      documentName: opts.documentName,
      signingUrl: opts.signingUrl,
      expiryDate,
      clientName: opts.clientName,
    })
  );
  const transporter = createTransporter();
  await transporter.sendMail({
    from: '"Teressa Copeland" <teressa@tcopelandhomes.com>',
    to: opts.to,
    subject: `Please sign: ${opts.documentName}`,
    html,
  });
}

export async function sendAgentNotificationEmail(opts: {
  clientName: string;
  documentName: string;
  signedAt: Date;
}): Promise<void> {
  const formattedTime = opts.signedAt.toLocaleString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    timeZoneName: 'short',
  });
  const transporter = createTransporter();
  await transporter.sendMail({
    from: '"Teressa Copeland Homes" <teressa@tcopelandhomes.com>',
    to: process.env.AGENT_EMAIL!,
    subject: `Signed: ${opts.documentName}`,
    text: `${opts.clientName} has signed "${opts.documentName}" on ${formattedTime}.`,
  });
}

export async function sendSignerCompletionEmail(opts: {
  to: string;
  documentName: string;
  downloadUrl: string;
}): Promise<void> {
  const transporter = createTransporter();
  await transporter.sendMail({
    from: '"Teressa Copeland Homes" <teressa@tcopelandhomes.com>',
    to: opts.to,
    subject: `Signed copy ready: ${opts.documentName}`,
    text: [
      `All parties have signed "${opts.documentName}".`,
      '',
      'Download your signed copy using the link below (expires in 72 hours):',
      opts.downloadUrl,
    ].join('\n'),
  });
}
