"use client";

import {
  createContext,
  type ReactNode,
  useContext,
  useEffect,
  useRef,
  useState,
} from "react";

import {
  createSplashLatestMessageCache,
  type SplashLatestMessageCache,
} from "@/lib/chat/splash_latest_message_cache";
import { useAuthState } from "@/stores/auth/auth-context";

const SplashLatestMessageCacheContext =
  createContext<SplashLatestMessageCache | null>(null);

export function SplashLatestMessageProvider({
  children,
}: {
  children: ReactNode;
}) {
  const [cache] = useState(createSplashLatestMessageCache);

  return (
    <SplashLatestMessageCacheContext.Provider value={cache}>
      <SplashLatestMessageAuthSync cache={cache} />
      {children}
    </SplashLatestMessageCacheContext.Provider>
  );
}

export function useSplashLatestMessageCache(): SplashLatestMessageCache {
  const cache = useContext(SplashLatestMessageCacheContext);
  if (!cache) {
    throw new Error(
      "useSplashLatestMessageCache must be used within SplashLatestMessageProvider.",
    );
  }
  return cache;
}

function SplashLatestMessageAuthSync({
  cache,
}: {
  cache: SplashLatestMessageCache;
}) {
  const authState = useAuthState();
  const previousLoginStatusRef = useRef<string | null>(null);

  useEffect(() => {
    if (!authState.hasInitialized || authState.isLoading) return;

    const previousLoginStatus = previousLoginStatusRef.current;
    if (
      previousLoginStatus !== null &&
      previousLoginStatus !== authState.loginStatus
    ) {
      cache.clear();
    }
    previousLoginStatusRef.current = authState.loginStatus;
  }, [
    authState.hasInitialized,
    authState.isLoading,
    authState.loginStatus,
    cache,
  ]);

  return null;
}
