import nodemailer from 'nodemailer';

function getTransporter() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT ?? 587),
    secure: Number(process.env.SMTP_PORT ?? 587) === 465,
    auth: process.env.SMTP_USER
      ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD }
      : undefined,
  });
}

type SendProofEmailArgs = {
  to: string;
  customerName: string | null;
  link: string;
  productName: string;
  note: string | null;
};

export async function sendProofEmail({ to, customerName, link, productName, note }: SendProofEmailArgs) {
  if (!process.env.SMTP_HOST) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const greeting = customerName ? `Hi ${customerName},` : 'Hi,';
  const noteLine = note ? `\n\nA note from us: "${note}"` : '';

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject: `Your ${productName} design is ready to review`,
      text: `${greeting}\n\nYour ${productName} design is ready to review and approve:\n${link}${noteLine}\n\n— Craft2Prints`,
      html: `<p>${greeting}</p><p>Your ${productName} design is ready to review and approve:</p><p><a href="${link}">${link}</a></p>${
        note ? `<p>A note from us: <em>${note}</em></p>` : ''
      }<p>— Craft2Prints</p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendPasswordResetEmailArgs = {
  to: string;
  name: string | null;
  link: string;
};

export async function sendPasswordResetEmail({ to, name, link }: SendPasswordResetEmailArgs) {
  if (!process.env.SMTP_HOST) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const greeting = name ? `Hi ${name},` : 'Hi,';

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject: 'Reset your Craft2Prints password',
      text: `${greeting}\n\nUse the link below to reset your password. It expires in 1 hour.\n${link}\n\nIf you didn't request this, you can ignore this email.\n\n— Craft2Prints`,
      html: `<p>${greeting}</p><p>Use the link below to reset your password. It expires in 1 hour.</p><p><a href="${link}">${link}</a></p><p>If you didn't request this, you can ignore this email.</p><p>— Craft2Prints</p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendCustomRequestNotificationArgs = {
  customerName: string;
  productName: string;
  note: string | null;
  adminLink: string;
};

export async function sendCustomRequestNotification({
  customerName,
  productName,
  note,
  adminLink,
}: SendCustomRequestNotificationArgs) {
  const to = process.env.ADMIN_NOTIFY_EMAIL ?? process.env.SMTP_USER;
  if (!process.env.SMTP_HOST || !to) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const noteLine = note ? `\n\nTheir note: "${note}"` : '';

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject: `New photo request from ${customerName}`,
      text: `${customerName} sent in a photo for a ${productName}.${noteLine}\n\nReview it here:\n${adminLink}`,
      html: `<p>${customerName} sent in a photo for a ${productName}.</p>${
        note ? `<p>Their note: <em>${note}</em></p>` : ''
      }<p><a href="${adminLink}">${adminLink}</a></p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendContactMessageNotificationArgs = {
  name: string;
  email: string;
  message: string;
};

export async function sendContactMessageNotification({ name, email, message }: SendContactMessageNotificationArgs) {
  const to = process.env.ADMIN_NOTIFY_EMAIL ?? process.env.SMTP_USER;
  if (!process.env.SMTP_HOST || !to) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      replyTo: email,
      subject: `New contact message from ${name}`,
      text: `${name} (${email}) sent a message via the contact page:\n\n${message}`,
      html: `<p>${name} (${email}) sent a message via the contact page:</p><p>${message.replace(/\n/g, '<br>')}</p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendCustomerBroadcastArgs = {
  to: string;
  name: string | null;
  subject: string;
  message: string;
  attachment?: { filename: string; content: Buffer; contentType?: string } | null;
};

export async function sendCustomerBroadcast({ to, name, subject, message, attachment }: SendCustomerBroadcastArgs) {
  if (!process.env.SMTP_HOST) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const greeting = name ? `Hi ${name},` : 'Hi,';
  const htmlMessage = message.replace(/\n/g, '<br>');

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject,
      text: `${greeting}\n\n${message}\n\n— Craft2Prints\n\nYou're receiving this because you're on our Craft2Prints mailing list.`,
      html: `<p>${greeting}</p><p>${htmlMessage}</p><p>— Craft2Prints</p><p style="font-size:12px;color:#888">You're receiving this because you're on our Craft2Prints mailing list.</p>`,
      attachments: attachment ? [attachment] : undefined,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendDesignSubmissionNotificationArgs = {
  customerName: string | null;
  productName: string;
  adminLink: string;
};

export async function sendDesignSubmissionNotification({
  customerName,
  productName,
  adminLink,
}: SendDesignSubmissionNotificationArgs) {
  const to = process.env.ADMIN_NOTIFY_EMAIL ?? process.env.SMTP_USER;
  if (!process.env.SMTP_HOST || !to) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject: `New design submitted for approval${customerName ? ` from ${customerName}` : ''}`,
      text: `A new ${productName} design has been submitted for your review and approval.\n\nReview it here:\n${adminLink}`,
      html: `<p>A new ${productName} design has been submitted for your review and approval.</p><p><a href="${adminLink}">${adminLink}</a></p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendDesignApprovedEmailArgs = {
  to: string;
  customerName: string | null;
  productName: string;
  checkoutLink: string;
};

export async function sendDesignApprovedEmail({
  to,
  customerName,
  productName,
  checkoutLink,
}: SendDesignApprovedEmailArgs) {
  if (!process.env.SMTP_HOST) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const greeting = customerName ? `Hi ${customerName},` : 'Hi,';

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to,
      subject: `Your ${productName} design has been approved!`,
      text: `${greeting}\n\nYour ${productName} design has been approved! You can now add it to your cart and proceed to checkout.\n\n${checkoutLink}\n\n— Craft2Prints`,
      html: `<p>${greeting}</p><p>Your ${productName} design has been approved! You can now add it to your cart and proceed to checkout.</p><p><a href="${checkoutLink}">${checkoutLink}</a></p><p>— Craft2Prints</p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}

type SendDesignReadyForReviewArgs = {
  customerName: string;
  customerEmail: string;
  productName: string;
  reviewLink: string;
};

export async function sendDesignReadyForReview({
  customerName,
  customerEmail,
  productName,
  reviewLink,
}: SendDesignReadyForReviewArgs) {
  if (!process.env.SMTP_HOST) {
    return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
  }

  const transporter = getTransporter();

  const greeting = customerName ? `Hi ${customerName},` : 'Hi,';

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
      to: customerEmail,
      subject: `Your ${productName} design is ready for review`,
      text: `${greeting}\n\nYour ${productName} design is ready for you to review and approve.\n\nReview it here:\n${reviewLink}\n\nYou can approve the design to proceed to checkout, or request changes from the admin.\n\n— Craft2Prints`,
      html: `<p>${greeting}</p><p>Your ${productName} design is ready for you to review and approve.</p><p><a href="${reviewLink}">${reviewLink}</a></p><p>You can approve the design to proceed to checkout, or request changes from the admin.</p><p>— Craft2Prints</p>`,
    });
    return { sent: true as const };
  } catch (err) {
    return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
  }
}
