/* eslint-disable no-console */
const { createTransport } = require('nodemailer')
const { Client } = require('pg')
const jwt = require('jsonwebtoken')

const SENDER = 'support@sagefy.org'

const transport = createTransport(
  {
    host: 'smtp.sparkpostmail.com',
    port: 587,
    // secure: true,
    auth: {
      user: 'SMTP_Injection',
      pass: process.env.MAIL_PASS,
    },
  },
  {
    from: SENDER,
  }
)

async function sendMail({ to, subject, body }) {
  if (process.env.NODE_ENV === 'test') return Promise.resolve()
  try {
    return await transport.sendMail({
      to,
      subject,
      text: body,
    })
  } catch (e) {
    console.log('Did not send mail.', e)
    return Promise.resolve()
  }
}

const FOOTER_TEXT = `
This is a transactional email from Sagefy.
We are required to notify you of sign ups, password changes,
and any security incidents while you have an account.
If you would like to unsubscribe from other types of notices
or if you would like to delete your account,
please reply to this email and let us know.
We will fulfill your request within 10 business days.
`
const WELCOME_SUBJECT = 'Welcome to Sagefy'
const WELCOME_TEXT = `
Welcome to Sagefy!

If you did not create this account, please reply immediately.

If you are interested in biweekly updates on Sagefy's progress,
sign up at https://sgef.cc/devupdates

Thank you!

${FOOTER_TEXT}
`
const PASSWORD_TOKEN_SUBJECT = 'Sagefy - Verification Request'
const PASSWORD_TOKEN_TEXT = `
To verify and update your account, please visit:
https://sagefy.org/password?state=2&token={token}

If you did not request a password change, please reply immediately.

${FOOTER_TEXT}
`
const EMAIL_TOKEN_SUBJECT = 'Sagefy - Verification Request'
const EMAIL_TOKEN_TEXT = `
To verify and update your account, please visit:
https://sagefy.org/email?state=2&token={token}

If you did not request an email change, please reply immediately.

${FOOTER_TEXT}
`
const EMAIL_SUBJECT = 'Sagefy - Email Updated'
const EMAIL_TEXT = `
You updated your Sagefy email.

If you did not change your email, please reply immediately.

${FOOTER_TEXT}
`
const PASSWORD_SUBJECT = 'Sagefy - Password Updated'
const PASSWORD_TEXT = `
You updated your Sagefy password.

If you did not change your password, please reply immediately.

${FOOTER_TEXT}
`

module.exports = async function mailer() {
  // Why not use a shared pool with postgraphile?
  // https://github.com/brianc/node-pg-pool/issues/40
  const client = new Client({
    user: process.env.DB_USER || 'sg_postgraphile',
    host: process.env.DB_HOST || 'postgres',
    database: process.env.DB_DATABASE || 'sagefy',
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT || 5432,
  })

  await client.connect()

  await client.query('LISTEN create_user')
  await client.query('LISTEN send_email_token')
  await client.query('LISTEN send_password_token')
  await client.query('LISTEN update_email')
  await client.query('LISTEN update_password')

  client.on('notification', async msg => {
    if (msg.channel === 'create_user') {
      await sendMail({
        to: msg.payload,
        subject: WELCOME_SUBJECT,
        body: WELCOME_TEXT,
      })
    }
    if (msg.channel === 'send_password_token') {
      const [to, userId, uniq] = msg.payload.split(' ')
      const token = jwt.sign(
        { user_id: userId, uniq },
        process.env.JWT_SECRET,
        { expiresIn: '1h', audience: 'postgraphile' }
      )
      await sendMail({
        to,
        subject: PASSWORD_TOKEN_SUBJECT,
        body: PASSWORD_TOKEN_TEXT.replace('{token}', token),
      })
    }
    if (msg.channel === 'send_email_token') {
      const [to, userId, uniq] = msg.payload.split(' ')
      const token = jwt.sign(
        { user_id: userId, uniq },
        process.env.JWT_SECRET,
        { expiresIn: '1h', audience: 'postgraphile' }
      )
      await sendMail({
        to,
        subject: EMAIL_TOKEN_SUBJECT,
        body: EMAIL_TOKEN_TEXT.replace('{token}', token),
      })
    }
    if (msg.channel === 'update_email') {
      await sendMail({
        to: msg.payload,
        subject: EMAIL_SUBJECT,
        body: EMAIL_TEXT,
      })
    }
    if (msg.channel === 'update_password') {
      await sendMail({
        to: msg.payload,
        subject: PASSWORD_SUBJECT,
        body: PASSWORD_TEXT,
      })
    }
  })
}

@@ -186,539 +186,8 @@
 g'%0A%0A
-const transport = createTransport(%0A  %7B%0A    host: 'smtp.sparkpostmail.com',%0A    port: 587,%0A    // secure: true,%0A    auth: %7B%0A      user: 'SMTP_Injection',%0A      pass: process.env.MAIL_PASS,%0A    %7D,%0A  %7D,%0A  %7B%0A    from: SENDER,%0A  %7D%0A)%0A%0Aasync function sendMail(%7B to, subject, body %7D) %7B%0A  if (process.env.NODE_ENV === 'test') return Promise.resolve()%0A  try %7B%0A    return await transport.sendMail(%7B%0A      to,%0A      subject,%0A      text: body,%0A    %7D)%0A  %7D catch (e) %7B%0A    console.log('Did not send mail.', e)%0A    return Promise.resolve()%0A  %7D%0A%7D%0A%0A
 cons
@@ -1769,16 +1769,547 @@
 EXT%7D%0A%60%0A%0A
+const transport = createTransport(%0A  %7B%0A    host: 'smtp.sparkpostmail.com',%0A    port: 587,%0A    // secure: true,%0A    auth: %7B%0A      user: 'SMTP_Injection',%0A      pass: process.env.MAIL_PASS,%0A    %7D,%0A  %7D,%0A  %7B%0A    from: SENDER,%0A  %7D%0A)%0A%0Aasync function sendMail(%7B to, subject, body %7D) %7B%0A  if (process.env.NODE_ENV === 'test') return Promise.resolve()%0A  try %7B%0A    return await transport.sendMail(%7B%0A      to,%0A      subject,%0A      text: body,%0A    %7D)%0A  %7D catch (e) %7B%0A    console.log('Did not send mail.', e)%0A    return Promise.resolve()%0A  %7D%0A%7D%0A%0A
 module.e

Update mail.js