import { decodeJwt } from 'jose'

import { userTokenCookieConfig } from '~/libs/cookie.server'

type TTokenCookie = {
  token: string
}

export const generateTokenCookie = (parameters: TTokenCookie) => {
  const { token } = parameters

  const decodedToken = decodeJwt(token)
  const decodedTokenExp = decodedToken.exp
  const expirationDate = decodedTokenExp
    ? new Date(decodedTokenExp * 1000)
    : undefined

  return userTokenCookieConfig.serialize(token, {
    expires: expirationDate,
  })
}
