import type { Session, User } from 'lucia'
import fp from 'fastify-plugin'
import { auth } from '../auth/lucia.ts'

declare module 'fastify' {
  interface FastifyRequest {
    user: User | null
    session: Session | null
  }
}

export default fp(async (fastify) => {
  fastify.decorateRequest('user', null)
  fastify.decorateRequest('session', null)

  fastify.addHook('preHandler', async (req, reply) => {
    try {
      const sessionId = auth.readSessionCookie(req.headers.cookie ?? '')

      if (!sessionId)
        return

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

      if (session && session.fresh) {
        const cookie = auth.createSessionCookie(session.id)

        reply.setCookie(cookie.name, cookie.value, cookie.attributes)
      }

      if (!session) {
        const blank = auth.createBlankSessionCookie()

        reply.setCookie(blank.name, blank.value, blank.attributes)
      }

      req.user = user
      req.session = session
    }
    catch {
      req.user = null
      req.session = null
    }
  })
})
