import getTokenDB from "@backend/components/getTokenDB"
import getTokenFromCookie from "@backend/components/getTokenFromCookie"
import sendError from "@backend/components/sendError"
import sendResponse from "@backend/components/sendResponse"
import decodeToken from "@lib/backend/components/decodeToken"
import type { NextApiRequest, NextApiResponse } from "next"

interface Data {
  loggedOut: boolean
}

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

  const { refreshToken } = await getTokenFromCookie(context)
  const token = await decodeToken(context, refreshToken)
  const tokenDB = await getTokenDB(context, token, true)

  return sendResponse(context, {
    message: "User of Token " + tokenDB.id + " logged out.",
    body: { loggedOut: true },
    type: ["debug", "infoCyan"],
    cookie: "",
  })
}
