type ProfilePhotoMessageLike = {
  createdByProfile?: unknown;
};

export default function useProfilePhotoSrc() {
  const { API_DO_STORAGE_ENDPOINT } = useRuntimeConfig().public;

  const isProbablyUrl = (value: string) =>
    /^(https?:\/\/|data:|blob:)/i.test(value);

  const trimSlashes = (value: string) => value.replace(/^\/+|\/+$/g, "");

  const joinUrl = (base: string, ...parts: string[]) => {
    const safeBase = base.replace(/\/+$/g, "");
    const safeParts = parts.map((p) => trimSlashes(p)).filter(Boolean);
    return [safeBase, ...safeParts].join("/");
  };

  const getProfilePhotoSrc = (message: ProfilePhotoMessageLike) => {
    const rawKey = message?.createdByProfile;
    if (typeof rawKey !== "string") return "";

    const key = rawKey.trim();
    if (!key) return "";

    if (isProbablyUrl(key)) return key;

    return joinUrl(String(API_DO_STORAGE_ENDPOINT || ""), key);
  };

  return {
    getProfilePhotoSrc,
  };
}
