'use server';

import { getMailer } from '@kit/mailers';
import { enhanceAction } from '@kit/next/actions';
import { getLogger } from '@kit/shared/logger';
import { toArray } from '@kit/shared/utils';

import { emailSchema } from '~/lib/validations/email.schema';

type EmailTemplate = {
  html: string;
  subject: string;
};

export type EmailRenderer<T = any> = (params: T) => Promise<EmailTemplate>;

export const sendEmailFromTemplate = async <T>(
  renderer: EmailRenderer<T>,
  templateParams: T,
  recipients: string | string[],
) => {
  const { html, subject } = await renderer(templateParams);

  const recipientsArray = toArray(recipients);
  if (!recipientsArray.length) {
    throw new Error('No valid email recipients provided');
  }

  const emailPromises = recipientsArray.map((email) =>
    sendEmail({
      subject,
      html,
      to: email,
    }),
  );

  await Promise.all(emailPromises);
};

export const sendEmail = enhanceAction(
  async ({ subject, html, to }) => {
    const mailer = await getMailer();
    const log = await getLogger();

    if (!process.env.EMAIL_USER) {
      log.error('Sending email failed, as no sender was found in env.');
      throw new Error('No email user configured');
    }

    const result = await mailer.sendEmail({
      from: process.env.EMAIL_USER,
      to,
      subject,
      html,
    });

    log.info(
      `Sent email with subject "${subject}", result: ${JSON.stringify(result)}`,
    );

    return {};
  },
  {
    schema: emailSchema,
    auth: false,
  },
);
