import type { MediaAsset } from "@/types/media";

export function parseSupabaseStorageObjectUrl(
  fileUrl: string,
): { bucket: string; path: string } | null {
  try {
    const url = new URL(fileUrl);
    const segments = url.pathname.split("/").filter(Boolean);
    const objectIdx = segments.findIndex((seg) => seg === "object");
    if (objectIdx === -1 || objectIdx + 2 >= segments.length) return null;
    const mode = segments[objectIdx + 1];
    if (mode !== "public" && mode !== "sign") return null;
    const bucket = segments[objectIdx + 2];
    const p = segments.slice(objectIdx + 3).join("/");
    return p ? { bucket, path: p } : null;
  } catch {
    return null;
  }
}

export function isRealFileAsset(asset: MediaAsset): boolean {
  if (Boolean(asset.storage_path)) return true;
  const url = asset.file_url ?? "";
  if (!url.startsWith("http")) return false;
  return parseSupabaseStorageObjectUrl(url) !== null;
}

