import type { CookieOptions, Response } from 'express'
import type { ActorType } from './tokens'

const COOKIE_NAMES: Record<ActorType, string> = {
  admin: 'admin_session',
  employee: 'employee_session',
  renter: 'renter_session',
}

export function getSessionCookieName(actorType: ActorType) {
  return COOKIE_NAMES[actorType]
}

function getSessionCookieOptions(actorType: ActorType, maxAgeMs?: number): CookieOptions {
  const domain = process.env.SESSION_COOKIE_DOMAIN?.trim()

  return {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: actorType === 'admin' ? 'strict' : 'lax',
    path: '/',
    ...(domain ? { domain } : {}),
    ...(maxAgeMs !== undefined ? { maxAge: maxAgeMs } : {}),
  }
}

export function setSessionCookie(res: Response, actorType: ActorType, token: string, maxAgeMs?: number) {
  res.cookie(getSessionCookieName(actorType), token, getSessionCookieOptions(actorType, maxAgeMs))
}

export function clearSessionCookie(res: Response, actorType: ActorType) {
  res.clearCookie(getSessionCookieName(actorType), getSessionCookieOptions(actorType))
}
