const { resp } = require('src/utils/response/index.js');
const redis = require('src/utils/redis.js');
const sso = require('src/utils/sso/index.js');
const { OPENID_EXPIRE } = require('src/constants/index.js');
const uuid = require('uuid');
const url = require('url');

const controller = {};
module.exports = controller;

controller.loginSSO = () => async ctx => {
  const { back_url: backURL } = ctx.query;

  const state = uuid.v4();

  const authURL = sso.getAuthURL(state);

  // store back url to cache
  const cacheKey = redis.Key.ssoLoginCache(state);

  await redis.set(cacheKey, JSON.stringify({ back_url: backURL }), 'EX', OPENID_EXPIRE);

  const u = new url.URL(authURL);

  ctx.resp(resp.Success, { url: u.toString() });
};

controller.logout = () => async ctx => {
  let link = '';

  if (ctx.token.sso) {
    link = sso.getLogoutURL();
  }

  ctx.resp(resp.Success, { url: link });
};

controller.getInfo = () => async ctx => {
  ctx.resp(resp.Success, {});
};