import { getCookie } from 'h3'
import { getDb } from '../utils/db.js'
import { skipAuth } from '../utils/authHelpers.js'

export default defineEventHandler(async (event) => {
  if (skipAuth(event.path)) return
  const sid = getCookie(event, 'session_id')
  if (!sid) return
  try {
    const { get } = await getDb()
    const session = await get('SELECT user_id, expires_at FROM sessions WHERE id = ?', [sid])
    if (!session || new Date(session.expires_at) < new Date()) return
    const user = await get('SELECT id, identifier, role, auth_provider, avatar_path FROM users WHERE id = ?', [session.user_id])
    if (user) {
      const authProvider = user.auth_provider ?? 'local'
      event.context.user = {
        id: user.id,
        identifier: user.identifier,
        role: user.role,
        auth_provider: authProvider,
        avatar_path: user.avatar_path ?? null,
      }
    }
  }
  catch {
    // ignore db errors; context stays unset
  }
})
