import logging, { Logging } from "../logging"
import { RawToken, tokenLifetime } from "./createTokenDB"
import type { API } from "./sendError"
import { deleteCookie, setCookie } from "cookies-next"

export interface Result<T> {
  message: string
  statusCode?: number
  body?: T
  type?: Logging[]
  cookie?: string
}

export default function sendResponse<T>(context: API<T>, result: Result<T>) {
  const { req, res } = context
  if (typeof result.cookie === "string") {
    if (result.cookie) {
      console.log(1)
      setCookie("token", result.cookie, {
        req,
        res,
        maxAge: tokenLifetime.REFRESH,
        httpOnly: true,
        sameSite: true,
        secure: true,
        path: "/api",
      })
    } else {
      console.log(2)
      deleteCookie("token", {
        req,
        res,
        path: "/api",
      })
    }
  }
  res.status(result.statusCode ?? 200)
  result.body ? res.json(result.body) : res.end()
  logging(result.message, result.type ?? ["debug"], req)
  return "done" as const
}
