import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

const PREFIX = 'https://www.googleapis.com/auth';
const SCOPES = [
  `${PREFIX}/youtube.force-ssl`,
  `${PREFIX}/youtube.upload`,
  `${PREFIX}/youtube ${PREFIX}/yt-analytics-monetary.readonly`,
].join(' ');

function GoogleAuth() {
  const router = useRouter();
  const { cid, code } = router.query;

  useEffect(() => {
    if (cid) {
      router.replace({
        pathname: 'https://accounts.google.com/o/oauth2/v2/auth',
        query: {
          client_id: cid,
          redirect_uri: `${window.location.origin}/auth/google`,
          response_type: 'code',
          scope: SCOPES,
          access_type: 'offline',
          include_granted_scopes: true,
          prompt: 'consent',
        },
      });
    }

    if (code) {
      window.opener.postMessage({ type: 'ac_auth_g', code }, '*');
      window.close();
    }
  }, []);

  // eslint-disable-next-line react/jsx-no-useless-fragment
  return <></>;
}

export default GoogleAuth;
