import { MatrixClient } from 'matrix-js-sdk';
import { isNativePlatform } from './capacitor';

// Mirrors the Java-side key constants in CallDeclineReceiver. Capacitor
// Preferences default group lands in shared_prefs/CapacitorStorage.xml under
// MODE_PRIVATE (see node_modules/@capacitor/preferences PreferencesConfiguration).
const SESSION_KEY = 'vojo.matrixSession';

// Synapse here ships without MSC2918 refresh tokens (docs/ai/server-side.md
// homeserver.yaml has no session_lifetime) and initClient() never wires
// tokenRefreshFunction — access tokens don't rotate. One write at client
// mount + one clear at logout is the whole lifecycle.
export const writeSessionBridge = async (mx: MatrixClient): Promise<void> => {
  if (!isNativePlatform()) return;
  const accessToken = mx.getAccessToken();
  const { baseUrl } = mx;
  const userId = mx.getUserId();
  if (!accessToken || !baseUrl || !userId) return;
  try {
    const { Preferences } = await import('@capacitor/preferences');
    await Preferences.set({
      key: SESSION_KEY,
      value: JSON.stringify({ accessToken, baseUrl, userId }),
    });
  } catch {
    /* non-fatal — receiver falls back to null-prefs path (preserves ring) */
  }
};

export const clearSessionBridge = async (): Promise<void> => {
  if (!isNativePlatform()) return;
  try {
    const { Preferences } = await import('@capacitor/preferences');
    await Preferences.remove({ key: SESSION_KEY });
  } catch {
    /* ignore */
  }
};
