import { Strategy } from 'passport-google-oauth20'

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

import genericStrategy from '../strategy'

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

const strategyOptions = {
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: callbackURL,
}

export function googleStrategy() {
  return new Strategy(strategyOptions, genericStrategy('google'))
}

export const googleRouter = Router()

const googleAuthenticateOptions = {
  scope: ['email', 'profile'],
}

googleRouter.get('/google', passport.authenticate('google', googleAuthenticateOptions))
googleRouter.get(
  '/google/redirect',
  passport.authenticate('google', { successRedirect: '/museo', failureRedirect: '/' }),
)
