"use client";

import type { ChatMediaKind } from "@/data/dto/chat";
import { getChatRepository } from "@/data/repositories/chat_repository";
import { Result, type Result as ResultT } from "@/utils";

import { localChatMediaRowToBlob } from "./chat_media_blob";

export interface ResolveCachedChatMediaBlobInput {
  messageId: string;
  kind: ChatMediaKind;
}

export interface CacheRemoteChatMediaBlobInput
  extends ResolveCachedChatMediaBlobInput {
  remoteUrl: string;
}

export async function resolveCachedChatMediaBlob(
  input: ResolveCachedChatMediaBlobInput,
): Promise<ResultT<Blob | null>> {
  const result = await getChatRepository().getCachedMedia(input);
  if (Result.isErr(result)) return result;
  if (!result.data) return Result.ok(null);
  return Result.ok(localChatMediaRowToBlob(result.data));
}

export async function cacheRemoteChatMediaBlob(
  input: CacheRemoteChatMediaBlobInput,
): Promise<ResultT<Blob>> {
  const result = await getChatRepository().cacheRemoteMedia(input);
  if (Result.isErr(result)) return result;
  const blob = localChatMediaRowToBlob(result.data);
  if (!blob) return Result.err(new Error("Cached media has no readable bytes."));
  return Result.ok(blob);
}
