import { useFlueAgent } from "@flue/react";

import { usePersonalOrganization } from "@/hooks/use-personal-organization";
import type { PersonalOrganizationState } from "@/hooks/use-personal-organization";
import { CHAT_AGENT } from "@/lib/chat/constants";
import type { ChatAgentState } from "@/lib/chat/types";

export const useOrganizationChatAgent = (
  organization: PersonalOrganizationState
): ChatAgentState => {
  const agent = useFlueAgent({
    ...CHAT_AGENT,
    id: organization.organizationId,
  });

  const sendMessage = async (message: string): Promise<void> => {
    if (!organization.organizationId) {
      throw (
        organization.error ??
        new Error("Personal organization is still being prepared")
      );
    }
    await agent.sendMessage(message);
  };

  let { status } = agent;
  if (!organization.organizationId) {
    status = organization.error ? "error" : "connecting";
  }

  return {
    error: organization.error ?? agent.error,
    historyReady: agent.historyReady,
    messages: agent.messages,
    sendMessage,
    status,
  };
};

export const useChatAgent = (): ChatAgentState =>
  useOrganizationChatAgent(usePersonalOrganization());
