import { NextApiRequest, NextApiResponse } from "next"
import getTokenFromBody from "../../lib/backend/components/getTokenFromBody"
import checkTokenIsValid from "../../lib/backend/components/checkTokenIsValid"
import getTokenDB from "../../lib/backend/components/getTokenDB"
import getPlayerByIdDB from "../../lib/backend/components/getPlayerByIdDB"
import sendResponse from "../../lib/backend/components/sendResponse"
import sendError from "../../lib/backend/components/sendError"
import { Logging } from "../../lib/backend/logging"
import { Game, Player, Token } from "@prisma/client"

interface Data {
  games: Game[]
}

export default async function data(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  return getTokenFromBody({ req, res, tokenType: "ACCESS" as Token["type"] })
    .then(checkTokenIsValid)
    .then(getTokenDB)
    .then(getPlayerByIdDB)
    .then(dataResponse<Data>)
    .then(sendResponse<Data>)
    .catch((err) => sendError(req, res, err))
}

async function dataResponse<T>(payload: {
  player: Player
  tokenDB: Token
  // games: Game[],
  req: NextApiRequest
  res: NextApiResponse<T>
}) {
  const { player, tokenDB, req, res } = payload

  const games: any = {}
  // Successfull response
  return {
    req,
    res,
    result: {
      message:
        "Requested data of user: " +
        player.id +
        " with Access-Token: " +
        tokenDB.id,
      body: { games },
      type: ["debug", "info.cyan"] as Logging[],
    },
  }
}
