import { NextApiRequest, NextApiResponse } from "next"
import checkTokenIsValid from "../../lib/backend/components/checkTokenIsValid"
import sendResponse from "../../lib/backend/components/sendResponse"
import sendError from "../../lib/backend/components/sendError"
import { deleteCookie } from "cookies-next"
import { Token } from "@prisma/client"
import getTokenDB from "../../lib/backend/components/getTokenDB"
import getTokenFromCookie from "../../lib/backend/components/getTokenFromCookie"
import logging, { Logging } from "../../lib/backend/logging"

interface Data {
  loggedOut: boolean
}

export default async function logout(
  req: NextApiRequest,
  res: NextApiResponse<any>
) {
  return getTokenFromCookie({ req, res })
    .then(checkTokenIsValid)
    .then(getTokenDB)
    .then(logoutResponse<Data>)
    .then(sendResponse<Data>)
    .catch((err) => sendError(req, res, err))
}

async function logoutResponse<T>(payload: {
  tokenDB: Token
  req: NextApiRequest
  res: NextApiResponse<T>
}) {
  const { tokenDB, req, res } = payload

  // Set login cookie
  deleteCookie("token", { req, res })

  // Successfull response
  return {
    req,
    res,
    result: {
      message: "User of Token " + tokenDB.id + " logged out.",
      body: { loggedOut: true },
      type: ["debug", "info.cyan"] as Logging[],
    },
  }
}
