import { useNavigate } from 'react-router';
import { useQuery } from '@tanstack/react-query';
import { createContext, use, type PropsWithChildren } from 'react';
import { useApi } from './ApiProvider';
import { useResponseErrorHandler } from '../hooks/ResponseHelper';
import type { Schemas } from '../generated/api-client/api-client';

export type HealthStatus = Schemas.HealthInfo;

export type ApiHealthProviderProps = PropsWithChildren<object>;
export type ApiHealthContextType = {
  healthStatus: HealthStatus | undefined;
};

const ApiHealthContext = createContext<ApiHealthContextType | null>(null);

export const ApiHealthProvider: React.FC<ApiHealthProviderProps> = ({ children }) => {
  const navigate = useNavigate();
  const { tanstackApiClient } = useApi();
  const { defaultResponseErrorHandler } = useResponseErrorHandler();

  const { queryOptions: healthInfoQuery } = tanstackApiClient.get('/api/health/info');
  const { data } = useQuery({
    ...healthInfoQuery,
    queryFn: async (...args) => {
      try {
        const data = await healthInfoQuery.queryFn!(...args);
        if (!data.is_initialized) {
          navigate('/init');
        }
        return data;
      } catch (error) {
        if (defaultResponseErrorHandler(error)) return {} as never;
        throw error;
      }
    },
  });

  return (
    <ApiHealthContext
      value={{
        healthStatus: data,
      }}
    >
      {children}
    </ApiHealthContext>
  );
};

export const useApiHealth = (): ApiHealthContextType => {
  const context = use(ApiHealthContext);
  if (!context) {
    throw new Error('useApiHealth must be used within an ApiHealthProvider');
  }
  return context;
};
