import path from 'path'

import { Strategy } from 'passport-facebook'

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

import genericStrategy from '../strategy'

const redirectPath = 'auth/facebook/redirect'
const callbackURL =
  process.env.NODE_ENV !== 'production'
    ? `${process.env.HOST_DEV}/${redirectPath}`
    : `${process.env.HOST}/${redirectPath}`

const strategyOptions = {
  clientID: process.env.FACEBOOK_CLIENT_ID,
  clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
  callbackURL: callbackURL,
  profileFields: ['id', 'displayName', 'picture.type(large)', 'email'],
}

export function facebookStrategy() {
  return new Strategy(strategyOptions, genericStrategy('facebook'))
}

export const facebookRouter = Router()

const facebookAuthenticateOptions = {
  authType: 'rerequest',
  scope: ['email'],
}

facebookRouter.get(
  '/facebook',
  passport.authenticate('facebook', facebookAuthenticateOptions),
)
facebookRouter.get(
  '/facebook/redirect',
  passport.authenticate('facebook', { successRedirect: '/museo', failureRedirect: '/' }),
)
