import {
  createImageUrlBuilder,
  type ImageUrlBuilder,
  type SanityImageSource,
} from "@sanity/image-url";

import { dataset, projectId } from "./env";

/**
 * Image URL builder for Sanity assets. Safe to import from RSC —
 * if projectId is missing this returns an empty-string shim so that
 * fallback renders never 500.
 */
const builder: ImageUrlBuilder | null = projectId
  ? createImageUrlBuilder({ projectId, dataset })
  : null;

type UrlForReturn = {
  url: () => string;
  width: (w: number) => UrlForReturn;
  height: (h: number) => UrlForReturn;
  fit: (fit: string) => UrlForReturn;
};

const emptyShim: UrlForReturn = {
  url: () => "",
  width: () => emptyShim,
  height: () => emptyShim,
  fit: () => emptyShim,
};

export function urlFor(source: SanityImageSource | null | undefined): UrlForReturn {
  if (!builder || !source) return emptyShim;
  return builder.image(source) as unknown as UrlForReturn;
}
