import config from '@madbean/config';
import Auth0Strategy from 'passport-auth0';
import passport from 'passport';
import connectEnsureLogin from 'connect-ensure-login';
import session from 'express-session';
import jwt from 'jsonwebtoken';
import fs from 'fs';

import { userMapper } from '../Mapper';
import { updateOrSaveUser } from '../api';

export default (app, account, home) => {
  const {
    ensureLoggedIn,
  } = connectEnsureLogin;

  const isDev = process.env.NODE_ENV_URL === 'local';

  const cert = isDev
    ? 'hive'
    : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/privkey.pem');

  const envUrl = isDev
    ? 'http://localhost:3000/callback'
    : 'https://authentication-dev.madbean.ovh/callback';

  const auth0Strategy = new Auth0Strategy({
    domain: config.auth.passport.domain,
    clientID: config.auth.passport.clientID,
    clientSecret: config.auth.passport.clientSecret,
    callbackURL: envUrl,
  }, (accessToken, refreshToken, extraParams, profile, done) => {
    console.log('cert', cert);
    const token = jwt.sign({ data: profile }, cert, {
      algorithm: 'RS256',
      expiresIn: 10080,
    });
    console.log(token);
    return done(null, { ...profile, token });
  });

  passport.use(auth0Strategy);

  passport.serializeUser((user, done) => {
    updateOrSaveUser(user);
    done(null, user);
  });

  passport.deserializeUser((user, done) => {
    done(null, user);
  });

  app.use(session({
    secret: 'hive',
    resave: false,
    saveUninitialized: true,
  }));
  app.use(passport.initialize());
  app.use(passport.session());

  app.get('/login/google', (req, res, next) => {
    const state = JSON.stringify({ prefix: req.query.prefix });
    passport.authenticate('auth0', { connection: 'google-oauth2', state })(req, res, next);
  });

  app.get(
    '/login/github',
    passport.authenticate('auth0', { connection: 'github' }), (req, res) => {}
  );

  app.get(
    '/login/facebook',
    passport.authenticate('auth0', { connection: 'facebook' }), (req, res) => {}
  );

  app.get('/logout', (req, res) => {
    req.logout();
    res.redirect('/home');
  });

  app.get('/callback', passport.authenticate('auth0', { failureRedirect: '/' }), (req, res) => {
    const { prefix } = JSON.parse(req.query.state);
    const jsonUser = JSON.stringify(userMapper(req.user));

    res.render('pages/success', {
      user: jsonUser,
      prefixer: prefix,
    });
  });

  app.get('/', home);
  app.get('/home', home);
  app.get('/account', ensureLoggedIn('/home'), account);
};
