/**
 * Auth mode helpers:
 *
 * Product shape (`NEXT_PUBLIC_MAILFORGE_PRODUCT`, baked at `next build`):
 * - **standalone** (default): no CRM embed — bootstrap session or native login.
 * - **embed**: host CRM issues `?token=` JWT; opt-in bootstrap via env flags.
 *
 * - **Bootstrap standalone** (`MAILFORGE_STANDALONE` or default in standalone product):
 *   one-shot session via `/api/auth/standalone/attach`.
 * - **Native login** (`MAILFORGE_NATIVE_AUTH`): `/login` + password in DB; CRM
 *   data via REST adapter (Settings / env).
 *
 * Native and bootstrap auto-session are mutually exclusive — native wins.
 */

function truthy(v: string | undefined): boolean {
  return v === 'true' || v === '1';
}

/** Baked at build — `embed` when integrating into a host CRM. */
export function isEmbeddedProductMode(): boolean {
  return process.env.NEXT_PUBLIC_MAILFORGE_PRODUCT === 'embed';
}

/** Mailforge UI login with email/password (stored in `users.password_hash`). */
export function isNativeAuthEnabled(): boolean {
  const server = process.env.MAILFORGE_NATIVE_AUTH?.trim().toLowerCase();
  if (server === 'false' || server === '0' || server === 'off' || server === 'no') {
    return false;
  }
  if (truthy(process.env.MAILFORGE_NATIVE_AUTH)) {
    return true;
  }
  // Standalone product: do NOT use baked NEXT_PUBLIC_* — old images otherwise
  // keep forcing /login even when runtime MAILFORGE_NATIVE_AUTH=false.
  if (!isEmbeddedProductMode()) {
    return false;
  }
  return truthy(process.env.NEXT_PUBLIC_MAILFORGE_NATIVE_AUTH);
}

/**
 * CRM-less auto session (no password) — when native login is off and either
 * `MAILFORGE_STANDALONE` is set or this is a **standalone product** build.
 */
export function isBootstrapStandaloneEnabled(): boolean {
  if (isNativeAuthEnabled()) return false;
  if (truthy(process.env.MAILFORGE_STANDALONE) || truthy(process.env.NEXT_PUBLIC_MAILFORGE_STANDALONE)) {
    return true;
  }
  if (!isEmbeddedProductMode()) return true;
  return false;
}

/** Same as `isBootstrapStandaloneEnabled` (backwards-compatible name). */
export function isStandaloneModeEnabled(): boolean {
  return isBootstrapStandaloneEnabled();
}
