import { linkBridge, registerWebMethod } from '@webview-bridge/web';
import { NavigateOptions } from 'react-router-dom';

import { AppBridge, AppPostMessageSchema } from './output';
import { router } from './shared/configs/sentry';

// Register functions in the registerWebMethod object in your web code
export const webBridge = registerWebMethod({
  async navigate(url: string, options?: NavigateOptions) {
    router.navigate(url, options);
  },
  async getPathname(): Promise<string> {
    return window.location.pathname;
  },
  async setLocalStorage(key: string, value: string) {
    localStorage.setItem(key, JSON.stringify(value));
  },
  async getLocalStorage(key: string): Promise<object | null> {
    const item = localStorage.getItem(key);
    return item && JSON.parse(item);
  },
  // ... Add more functions as needed
});

// Export the bridge type to be used in the web application
export type WebBridge = typeof webBridge;

export const bridge = linkBridge<AppBridge, AppPostMessageSchema>({
  throwOnError: true,
  onReady: () => {
    console.log('bridge is ready');
  },
});
