import { sendIfAllRecipientsEmailable } from '../external-services/emailSender.js';
import { SG_UNSUB_TRANSACTIONAL } from '../external-services/sendgrid.js';
import { declareHandler } from '../server-utils/routesHandler.js';

/**
 * This file contains all the route handers for the emails.
 *
 */

export const sendLoginEmail = declareHandler({
  func: async (req, res) => {
    const { email } = req.body;
    if (!email) return res.send({ success: false });
    sendIfAllRecipientsEmailable({
      from: { email: 'hello@wavtool.com' },
      replyTo: { email: 'hello@wavtool.com', name: 'WavTool' },
      personalizations: [{ to: [{ email }] }],
      templateId: 'd-bc76dad3773a438aa8e1790583dc9672',
      asm: { groupId: SG_UNSUB_TRANSACTIONAL },
    })
      .then(() => console.log('Welcome email sent successfully!'))
      .catch((e) => {
        console.error(e);
        throw e;
      });
    res.send({ success: true, email });
  },
});

export const sendMobileCouponEmail = declareHandler({
  func: async (req, res) => {
    const { email } = req.body;
    if (!email) return res.send({ success: false });
    sendIfAllRecipientsEmailable({
      from: { email: 'hello@wavtool.com' },
      replyTo: { email: 'hello@wavtool.com', name: 'WavTool' },
      personalizations: [{ to: [{ email }] }],
      templateId: 'd-5551ed72c5a24fc29b7128d0e1606f34',
      asm: { groupId: 20765 },
    })
      .then(() => console.log('Mobile coupon email sent successfully!'))
      .catch((e) => {
        console.error(e);
        throw e;
      });
    res.send({ success: true, email });
  },
});
