"use client";

import { useEffect, useState } from "react";

import { createAllChats } from "@/entities/chats/actions";
import { chatsService } from "@/services/chats";

export const useChatsInitialization = () => {
  const [isInitializing, setIsInitializing] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initializeChats = async () => {
      if (chatsService.isChatsInitialized()) {
        setIsInitialized(true);
        return;
      }

      setIsInitializing(true);
      setError(null);

      try {
        const response = await createAllChats();

        if (response.data?.success) {
          chatsService.setChatsInitialized();
          setIsInitialized(true);
        } else {
          setError("Chats initialization failed");
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : "Unknown error");
      } finally {
        setIsInitializing(false);
      }
    };

    initializeChats();
  }, []);

  return {
    isInitializing,
    isInitialized,
    error,
  };
};
