import { Injectable } from '@nestjs/common';
import YuFuId, { GAdminTokenName } from './lib/yufuid';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }

  async loginCallback(req, res) {
    const { code, state } = req.query;

    const tokenInfo = await YuFuId.getToken(code);
    const userInfo = await YuFuId.getUserInfo(tokenInfo.access_token);

    const expiresIn = 7 * 24 * 3600;
    const { user_id, sub, name, email } = userInfo;
    const payload = { user_id, sub, name, email };
    const token = await YuFuId.sign(payload, expiresIn);

    // append token param for local development
    const url = new URL(state);
    if (url.port != '') {
      url.searchParams.set(GAdminTokenName, token);
    }

    res.cookie(GAdminTokenName, token, {
      maxAge: expiresIn * 1000,
      httpOnly: false,
    });
    res.status(302).redirect(url.toString());
  }

  login(req, res) {
    const { redirect_url, ui_locales = 'zh-CN' } = req.query;

    // TODO: verify redirect_url domain

    const authorizeUrl = YuFuId.authorize(redirect_url, ui_locales);
    res.status(302).redirect(authorizeUrl);
  }

  logout(req, res) {
    const { redirect_url } = req.query;

    const logoutUrl = YuFuId.logout(redirect_url);
    res.cookie(GAdminTokenName);
    res.status(302).redirect(logoutUrl);
  }
}
