import dotenv from 'dotenv'
import path from 'path'
dotenv.config({ path: path.join(__dirname, '../../../.env') })

import { Router } from 'express'
import passport from 'passport'

import UserModel from '../models/user'
import { facebookRouter, facebookStrategy } from './providers/facebook'
import { googleRouter, googleStrategy } from './providers/google'
import { twitterRouter, twitterStrategy } from './providers/twitter'
import ensureAuthenticated from './middleware'

export function initPassport() {
  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser((id, done) => {
    UserModel.findById(id, (err, user) => {
      done(err, user)
    })
  })

  passport.use('facebook', facebookStrategy())
  passport.use('twitter', twitterStrategy())
  passport.use('google', googleStrategy())
}

export const authRouter = Router()
authRouter.use(facebookRouter)
authRouter.use(twitterRouter)
authRouter.use(googleRouter)

authRouter.get('/logout', function (req, res) {
  req.logout()
  res.redirect('/')
})

authRouter.get('/check', ensureAuthenticated, function (req, res) {
  res.json({ authenticated: true })
})
