import checkTokenIsValid from "@backend/components/checkTokenIsValid"
import getPlayerByIdDB from "@backend/components/getPlayerByIdDB"
import getTokenDB from "@backend/components/getTokenDB"
import getTokenFromCookie from "@backend/components/getTokenFromCookie"
import sendResponse from "@backend/components/sendResponse"
import type { NextApiRequest, NextApiResponse } from "next"

interface Data {
  token: string
}

export default async function auth(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const context = { req, res }

  const { refreshToken } = await getTokenFromCookie(context)
  const token = await checkTokenIsValid(context, refreshToken)
  const tokenDB = await getTokenDB(context, token)
  const player = await getPlayerByIdDB(context, tokenDB)
  return sendResponse(context, {
    message: "loginCheck -> true : " + player.id,
    type: ["debug", "infoCyan"],
  })
}
