import { createContext, useContext, useMemo } from 'react';
import type { ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchAppInfo, type AppRuntimeInfo, type RunMode } from '../api/appInfo';

const FALLBACK: AppRuntimeInfo = {
  runMode: 'Client',
  applicationName: 'Power Monitoring Portal',
  version: '0.0.0',
};

interface AppInfoContextValue {
  info: AppRuntimeInfo;
  isAdmin: boolean;
  isClient: boolean;
  loading: boolean;
}

const AppInfoContext = createContext<AppInfoContextValue | undefined>(undefined);

export function AppInfoProvider({ children }: { children: ReactNode }) {
  const { data, isLoading } = useQuery({
    queryKey: ['app-info'],
    queryFn: fetchAppInfo,
    staleTime: 5 * 60_000,
  });

  const info = useMemo<AppRuntimeInfo>(() => data ?? FALLBACK, [data]);
  const value = useMemo(
    () => ({
      info,
      isAdmin: info.runMode === 'Admin',
      isClient: info.runMode === 'Client',
      loading: isLoading,
    }),
    [info, isLoading],
  );

  return <AppInfoContext.Provider value={value}>{children}</AppInfoContext.Provider>;
}

export function useAppInfo(): AppInfoContextValue {
  const ctx = useContext(AppInfoContext);
  if (!ctx) throw new Error('useAppInfo must be used inside AppInfoProvider');
  return ctx;
}

export type { RunMode };
