import { getChatRepository } from "@/data/repositories/chat_repository";
import {
  resolveChatCacheOwnerKey,
  type ChatCacheIdentityResolver,
} from "@/data/repositories/chat_cache_identity";
import { Result, type Result as ResultT } from "@/utils/result";

import type { SplashLatestMessageCache } from "./splash_latest_message_cache";
import { getLatestSplashMessagePreview } from "./splash_latest_message_preview";

export interface LoadSplashLatestMessagePreviewInput {
  cache: SplashLatestMessageCache;
  fetchPreview?: () => Promise<ResultT<string | null>>;
  resolveIdentity?: ChatCacheIdentityResolver;
}

export async function resolveSplashLatestMessageCacheIdentity(): Promise<
  string | null
> {
  const result = await resolveChatCacheOwnerKey();
  return Result.isOk(result) ? result.data : null;
}

export async function loadSplashLatestMessagePreview({
  cache,
  fetchPreview = fetchSplashLatestMessagePreview,
  resolveIdentity = resolveChatCacheOwnerKey,
}: LoadSplashLatestMessagePreviewInput): Promise<ResultT<string | null>> {
  const identityResult = await resolveIdentity();
  const identity = Result.isOk(identityResult) ? identityResult.data : null;

  if (identity) {
    const cached = cache.get(identity);
    if (cached) return Result.ok(cached.message);
  }

  const result = await fetchPreview();
  if (identity && Result.isOk(result)) {
    cache.set(identity, result.data);
  }
  return result;
}

export async function fetchSplashLatestMessagePreview(): Promise<
  ResultT<string | null>
> {
  const result = await getChatRepository().getHistory(1, 0);
  if (Result.isErr(result)) return Result.err(result.error);

  return Result.ok(getLatestSplashMessagePreview(result.data.messages));
}
