import "server-only";

import { readFile } from "node:fs/promises";
import path from "node:path";

/**
 * Where `npm run import:wordpress` copied the WordPress images, so an import
 * can upload them from disk. Exists on a developer's machine, not on a
 * hosted admin panel; there the importer downloads `sourceUrl` instead.
 */
const storageRoot = path.resolve(process.cwd(), "storage", "uploads");

/** The stored file for a storage key, or null when it isn't there. */
export async function readStoredImage(storageKey: string) {
  const file = path.resolve(storageRoot, storageKey);
  if (!file.startsWith(storageRoot + path.sep)) return null;
  return readFile(file).then(
    (buffer) => new Uint8Array(buffer),
    () => null,
  );
}
