'use server';

import { getMailer } from '@kit/mailers';
import { enhanceAction } from '@kit/next/actions';

import { CompanySubmitData } from '../types/company';
import { emailSchema } from '../validations/email.schema';

export const sendCompanyOfferEmail = async (
  data: CompanySubmitData,
  language: string,
) => {
  const { renderCompanyOfferEmail } = await import('@kit/email-templates');
  const { html, subject, to } = await renderCompanyOfferEmail({
    language,
    companyData: data,
  });

  await sendEmail({
    subject,
    html,
    to,
  });
};

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

    await mailer.sendEmail({
      to,
      subject,
      html,
    });

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