/**
 * Advanced Example
 *
 * If you want to add custom routes or other behaviour with express in
 * conjuction with next-auth, you can pass an Express object to next-auth.
 * 
 * If you do, you will need to use express.all() to set Next.js as the default
 * route handler call express.listen() to start the express server.
 **/

// Include Next.js and Express
const express = require('express')
const next = require('next')
const nextAuth = require('next-auth')
const nextAuthOptions = require('./email/next-auth.config')

// Create instance of Express to use later 
const expressApp = express()
nextAuthOptions.express = expressApp

// Initialize Next.js and next-auth
const nextApp = next({
  dir: '.',
  dev: (process.env.NODE_ENV === 'development')
})

nextApp
.prepare()
.then(() => {
  return nextAuth.init(nextApp, nextAuthOptions)  
})
.then((expressSessions) => {
  // An example of how to interact with Express do do something like
  // add custom routing behaviour.
  expressApp.get('/blog/:id', (req, res) => {
    return nextApp.render(req, res, '/blog', req.params)
  })
  
  // Set Next.js to handle all routes (after setting any custom routes)
  expressApp.all('*', (req, res) => {
    let nextRequestHandler = nextApp.getRequestHandler()
    return nextRequestHandler(req, res)
  })

  // Start Express
  expressApp.listen(process.env.PORT, err => {
    if (err) throw err
    console.log(`Ready on http://localhost:${process.env.PORT || 3000}`)
  })
})
.catch(err => {
  console.log('An error occurred, unable to start the server')
  console.log(err)
})