'use strict';

const debug = require('debug')('egg-passport-dingtalk');
const assert = require('assert');
const Strategy = require('node-passport-dingtalk').Strategy;

module.exports = app => {
  const config = app.config.passportDingtalk;
  config.passReqToCallback = true;
  assert(config.key, '[egg-passport-twitter] config.passportDingtalk.key required');
  assert(config.secret, '[egg-passport-twitter] config.passportDingtalk.secret required');
  config.clientID = config.key;
  config.clientSecret = config.secret;

  // must require `req` params
  app.passport.use('dingtalk', new Strategy(config, (req, token, tokenSecret, params, profile, done) => {
    // format user
    const user = {
      provider: 'dingtalk',
      id: profile.id,
      name: profile.username,
      displayName: profile.displayName,
      photo: profile.photos && profile.photos[0] && profile.photos[0].value,
      token,
      tokenSecret,
      params,
      profile,
    };
    debug('%s %s get user: %j', req.method, req.url, user);

    // let passport do verify and call verify hook
    app.passport.doVerify(req, user, done);
  }));
};