import { decodeJwt } from 'jose'

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

type TTokenCookie = {
  token: string
}

export const generateUserTokenCookie = (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,
  })
}

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

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

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