/**
 * Auth cookie helpers — foundation-auth-rbac.
 *
 * Both cookies are HttpOnly; Secure; SameSite=Lax; domain=.zync.is (shared
 * across app/admin/api/www subdomains).
 *   - zync_session: access JWT, 1h lifetime.
 *   - zync_refresh: opaque refresh token (plaintext; DB stores its hash).
 *   - zync_admin:   admin access JWT, 1h lifetime.
 */
import type { Context } from 'hono'
import { deleteCookie, setCookie } from 'hono/cookie'
import { SESSION_TTL_SECONDS } from '@zync/auth'

export const SESSION_COOKIE = 'zync_session'
export const REFRESH_COOKIE = 'zync_refresh'
export const ADMIN_COOKIE = 'zync_admin'

const BASE = {
  httpOnly: true,
  secure: true,
  sameSite: 'Lax' as const,
  domain: '.zync.is',
  path: '/',
}

const REFRESH_TTL_SECONDS = 60 * 60 * 24 * 30 // 30 days

export function setSessionCookie(c: Context, token: string): void {
  setCookie(c, SESSION_COOKIE, token, { ...BASE, maxAge: SESSION_TTL_SECONDS })
}

export function setRefreshCookie(c: Context, token: string): void {
  setCookie(c, REFRESH_COOKIE, token, { ...BASE, maxAge: REFRESH_TTL_SECONDS })
}

export function setAdminCookie(c: Context, token: string): void {
  setCookie(c, ADMIN_COOKIE, token, { ...BASE, maxAge: SESSION_TTL_SECONDS })
}

export function clearAuthCookies(c: Context): void {
  deleteCookie(c, SESSION_COOKIE, { ...BASE })
  deleteCookie(c, REFRESH_COOKIE, { ...BASE })
}

/** Refresh-token lifetime in ms from now (for the DB expires_at column). */
export function refreshExpiry(): Date {
  return new Date(Date.now() + REFRESH_TTL_SECONDS * 1000)
}
