import { bo as getStorageProvider } from '../nitro/nitro.mjs';

const VARIANT_SIGNED_URL_EXPIRY_SECONDS = 3600;
function isCloudStorageProvider(provider) {
  return provider === "s3" || provider === "cloudflare-r2" || provider === "google-cloud";
}
function buildMediaFileUrl(id, useSignedRedirect = false) {
  const baseUrl = `/api/media/${id}/file`;
  return useSignedRedirect ? `${baseUrl}?redirect=true` : baseUrl;
}
function resolveMediaUrl(id, storageProvider, currentUrl) {
  if (isCloudStorageProvider(storageProvider)) {
    return buildMediaFileUrl(id, true);
  }
  if (typeof currentUrl === "string" && currentUrl.trim() !== "") {
    return currentUrl;
  }
  return buildMediaFileUrl(id);
}
function parseMediaFormats(value) {
  if (!value) {
    return null;
  }
  if (typeof value === "string") {
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  }
  if (typeof value === "object") {
    return value;
  }
  return null;
}
async function resolveSignedVariantFormats(value) {
  const formats = parseMediaFormats(value);
  if (!(formats == null ? void 0 : formats.variants)) {
    return formats;
  }
  const storage = getStorageProvider();
  if (!storage.supportsSignedUrls()) {
    return formats;
  }
  const signedVariants = await Promise.all(
    Object.entries(formats.variants).map(async ([name, variant]) => {
      const signedUrl = await storage.getSignedUrl(variant.path, {
        expiresIn: VARIANT_SIGNED_URL_EXPIRY_SECONDS
      });
      const nextVariant = {
        ...variant,
        url: signedUrl
      };
      return [name, nextVariant];
    })
  );
  return {
    variants: Object.fromEntries(signedVariants)
  };
}
async function enrichMediaDeliveryRecord(media) {
  var _a;
  const id = Number(media.id);
  if (!Number.isFinite(id) || id < 1) {
    return media;
  }
  const storageProvider = (_a = media.storageProvider) != null ? _a : media.storageprovider;
  const nextMedia = {
    ...media,
    url: resolveMediaUrl(id, storageProvider, media.url)
  };
  if (!isCloudStorageProvider(storageProvider)) {
    return nextMedia;
  }
  const signedFormats = await resolveSignedVariantFormats(media.formats);
  if (signedFormats) {
    nextMedia.formats = signedFormats;
  }
  return nextMedia;
}

export { resolveMediaUrl as a, enrichMediaDeliveryRecord as e, isCloudStorageProvider as i, parseMediaFormats as p, resolveSignedVariantFormats as r };
//# sourceMappingURL=media-delivery.mjs.map
