/**
 * Sets a cookie with sensible security defaults.
 *
 * Persistent sessions (mobile worker or PWA standalone) get a 30-day maxAge;
 * everything else stays as a browser-session cookie.
 *
 * `sameSite: 'lax'` and `secure: true` (in production) are applied to every
 * auth cookie. Cookies listed in HTTP_ONLY_COOKIES are additionally marked
 * httpOnly so they can never be read from JavaScript — only the server
 * consumes them.
 */
const MOBILE_MAX_AGE = 30 * 24 * 60 * 60 // 30 days in seconds

const HTTP_ONLY_COOKIES = new Set([
  'logship_it',       // access token — used only by fetchHelper
  'logship_rt',       // refresh token — used only by refreshTokenHelper
  'logship_session',  // server session id
])

const IS_PROD = process.env.NODE_ENV === 'production'

export default function setAuthCookie(event: any, name: string, value: any) {
  const cookieValue = (value !== null && typeof value === 'object') ? JSON.stringify(value) : value

  const isMobileWorker = getCookie(event, 'logship_mw')
  const isPwa = getCookie(event, 'logship_pwa')
  const persistent = isMobileWorker === '1' || isPwa === '1'

  const options: any = {
    path: '/',
    sameSite: 'lax',
    secure: IS_PROD,
  }
  if (persistent) options.maxAge = MOBILE_MAX_AGE
  if (HTTP_ONLY_COOKIES.has(name)) options.httpOnly = true

  setCookie(event, name, cookieValue, options)
}
