import { GetServerSidePropsContext, PreviewData } from "next"
import { ParsedUrlQuery } from "querystring"
import getTokenFromCookie from "../backend/components/getTokenFromCookie"
import checkTokenIsValid from "../backend/components/checkTokenIsValid"
import getTokenDB from "../backend/components/getTokenDB"
import getPlayerByIdDB from "../backend/components/getPlayerByIdDB"
import logging from "../backend/logging"

export default async function checkIsLoggedIn(
  context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>
) {
  const req: any = context.req
  const res: any = context.res

  const isLoggedIn = await getTokenFromCookie({ req, res })
    .then(checkTokenIsValid)
    .then(getTokenDB)
    .then(getPlayerByIdDB)
    .then(({ player }) => !!player)
    .catch(() => false)

  logging(
    "loginCheck " + (isLoggedIn ? true : "-> loggedIn: " + false),
    ["debug", "info.cyan"],
    req
  )

  return isLoggedIn
}
