// Session summary for the mobile profile modal (/mobile): who is logged in and in which
// context. Served from the auth cookies only (no iDempiere round-trip) so it also works
// offline-ish in the Capacitor app, where the cookies are synthesised from the Bearer token.
const readJsonCookie = (event: any, name: string): any => {
  const raw = getCookie(event, name)
  if (!raw) return null
  if (typeof raw !== 'string') return raw
  try { return JSON.parse(raw) } catch { return null }
}

export default defineEventHandler((event) => {
  const user = readJsonCookie(event, 'logship_user')
  if (!user) throw createError({ statusCode: 401, statusMessage: 'Not authenticated' })
  const org = readJsonCookie(event, 'logship_organization')
  const role = readJsonCookie(event, 'logship_role')
  const warehouse = readJsonCookie(event, 'logship_warehouse')
  const client = readJsonCookie(event, 'logship_client')
  return {
    id: user.id ?? Number(getCookie(event, 'logship_user_id')) ?? null,
    name: user.Name ?? user.name ?? '',
    // Login id (AD_User.Value); falls back to the name iDempiere also accepts as login
    login: user.Value ?? user.value ?? user.Name ?? '',
    email: user.EMail ?? user.email ?? '',
    organization: org?.Name ?? '',
    role: role?.Name ?? '',
    warehouse: warehouse?.Name ?? '',
    client: client?.Name ?? '',
    isMobileWorker: user.IsMobileWorker === true || user.IsMobileWorker === 'Y',
  }
})
