// ST-1002: HttpOnly pre-auth cookie voor de QR-pairing desktop-side.
//
// Wordt gezet door /api/auth/pair/start (ST-1003), gelezen door
// /api/auth/pair/stream/[id] (ST-1004) en /api/auth/pair/claim (ST-1006),
// en gewist op claim of cancel. Path-scoped naar /api/auth/pair zodat de
// cookie niet naar andere routes lekt.

import { cookies } from 'next/headers'

const COOKIE_NAME = 's4m_pair'
const MAX_AGE_SECONDS = 300 // gelijk aan pending-TTL van LoginPairing (5 min)
const COOKIE_PATH = '/api/auth/pair'

export async function setPairCookie(desktopToken: string): Promise<void> {
  const jar = await cookies()
  jar.set(COOKIE_NAME, desktopToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: COOKIE_PATH,
    maxAge: MAX_AGE_SECONDS,
  })
}

export async function readPairCookie(): Promise<string | null> {
  const jar = await cookies()
  return jar.get(COOKIE_NAME)?.value ?? null
}

export async function clearPairCookie(): Promise<void> {
  const jar = await cookies()
  jar.delete({ name: COOKIE_NAME, path: COOKIE_PATH })
}
