/**
 * Mobile worker enforcement shared by login.post.ts and select-role.post.ts.
 * The "Mobile Worker" checkbox on the signin page is only honored if the
 * user's ad_user record actually has IsMobileWorker = true — otherwise we
 * drop the flag and route them to the regular dashboard.
 */

function readMobileWorkerField(user: any): { key: string | null, raw: any } {
  if (!user || typeof user !== 'object') return { key: null, raw: undefined }
  for (const k of ['isMobileWorker', 'IsMobileWorker', 'ismobileworker', 'is_mobile_worker', 'IS_MOBILE_WORKER']) {
    if (k in user) return { key: k, raw: (user as any)[k] }
  }
  for (const key of Object.keys(user)) {
    if (key.toLowerCase().replace(/_/g, '') === 'ismobileworker') {
      return { key, raw: (user as any)[key] }
    }
  }
  return { key: null, raw: undefined }
}

function isTruthyIdempiereBool(v: any): boolean {
  if (v === true || v === 1) return true
  if (typeof v === 'string') {
    const s = v.trim().toLowerCase()
    return s === 'y' || s === 'true' || s === '1' || s === 'yes'
  }
  return false
}

export function isMobileWorkerUser(user: any): boolean {
  const { key, raw } = readMobileWorkerField(user)
  return !!key && isTruthyIdempiereBool(raw)
}

/**
 * Called after a login attempt finalizes. If `wantsMobile` is true but the
 * user's record says they're not a mobile worker, clears logship_mw and
 * stamps `data.mobileWorkerDenied = true`. Always stamps `data.mobileWorker`
 * with the authoritative boolean so the client can route without reading
 * cookies.
 */
export function enforceMobileWorkerGate(event: any, wantsMobile: boolean, user: any, data: any) {
  const actuallyAllowed = isMobileWorkerUser(user)
  data.mobileWorker = !!wantsMobile && actuallyAllowed

  if (!wantsMobile) return

  if (actuallyAllowed) return

  const mobileKeys = user && typeof user === 'object'
    ? Object.keys(user).filter(k => k.toLowerCase().includes('mobile'))
    : []
  const { key, raw } = readMobileWorkerField(user)
  console.warn(
    '[Mobile Worker] Gate denied. Requested mobileWorker=true but user record '
    + (key
        ? `has ${key}=${JSON.stringify(raw)} (not truthy).`
        : `does not expose an IsMobileWorker field. Mobile-ish keys on user: ${JSON.stringify(mobileKeys)}.`)
  )

  deleteCookie(event, 'logship_mw', { path: '/' })
  data.mobileWorkerDenied = true
}
