/*
 * Runtime Web – Unified Serverless Framework for Full-Stack TypeScript Applications
 * Documentation: https://runtimeweb.com/docs/getting-started
 *
 * @template: ai-chat
 */

import * as React from 'react';
import { ErrorBoundary, runtime, runtimeRouter } from '@worktif/runtime';

import { AiChatTies } from './ties/ai-chat.ties';
import { chatHandler, healthHandler, streamHandler } from './handlers/chat.handlers';

import runtimeConfig from 'runtime.config';

import App from './App';
import { routes } from './routes';

// Initialize Runtime Web application with AI Chat microservice support
runtime({
  app: ({ router }) => <App router={router} />,
  router: runtimeRouter({
    router: routes,
    defaults: {
      HydrateFallback: () => <div>Loading...</div>,
      ErrorBoundary: ({ error }: any) =>
        <ErrorBoundary>{error?.message || 'An unexpected error occurred. Please try again later.'}</ErrorBoundary>,
    },
  }),
  config: {
    serviceName:
      typeof window === 'undefined'
        ? process.env.RUNTIME_ENV_STACK_NAME || runtimeConfig.projectName
        : 'ai-chat-app',
    stage:
      typeof window === 'undefined'
        ? (process.env.RUNTIME_ENV_STAGE as 'dev' | 'staging' | 'prod')
        : 'dev',
  },

  // Microservice registry
  register: {
    // ================================================================
    // AI Chat Microservice
    // ================================================================
    chat: {
      ties: [AiChatTies],
      lambdas: [
        chatHandler,
        healthHandler,
        streamHandler,
      ],
    },
  },
});
