import Constants from 'expo-constants';
import { ConvexReactClient } from 'convex/react';

const getConvexUrl = (): string => {
  // Allow override via Expo extra config (set in app.config.ts for production)
  const fromConfig = Constants.expoConfig?.extra?.convexUrl as
    | string
    | undefined;
  if (fromConfig) return fromConfig;

  // Fall back to deriving from the dev server host (same pattern as getBaseUrl)
  const debuggerHost = Constants.expoConfig?.hostUri;
  const localhost = debuggerHost?.split(':')[0];

  if (!localhost) {
    throw new Error(
      'Could not determine Convex URL. Set extra.convexUrl in app.config.ts for production.',
    );
  }

  // Point at the self-hosted Convex backend on the local network
  // Update this port if your Convex backend runs on a different port
  return `http://${localhost}:3210`;
};

export const convex = new ConvexReactClient(getConvexUrl());
