import type { CreateExpressContextOptions } from '@trpc/server/adapters/express'
import { auth } from '../auth/lucia'

export async function createContext({ res, req }: CreateExpressContextOptions) {
  const sessionId = auth.readSessionCookie(req.headers.cookie ?? '')

  if (!sessionId)
    return { res, req }

  const { session, user } = await auth.validateSession(sessionId)

  if (session && session.fresh) {
    res.appendHeader('Set-Cookie', auth.createSessionCookie(session.id).serialize())
  }

  if (!session) {
    res.appendHeader('Set-Cookie', auth.createBlankSessionCookie().serialize())
  }

  return { res, req, session, user }
}

export type Context = Awaited<ReturnType<typeof createContext>>
