const getUploadsBasePath = (): string =>
  `/${(process.env.STORAGE_BASE_PATH ?? 'uploads').replace(/^\/+|\/+$/g, '')}/`;

export const resolveManagedFileUrl = (fileUrl: unknown): unknown => {
  if (typeof fileUrl !== 'string' || !fileUrl.trim()) {
    return fileUrl;
  }

  if (!fileUrl.startsWith(getUploadsBasePath())) {
    return fileUrl;
  }

  const baseUrl = (process.env.PUBLIC_BASE_URL ?? '').replace(/\/$/, '');
  if (!baseUrl) {
    return fileUrl;
  }

  return `${baseUrl}${fileUrl}`;
};

export const resolveManagedFileUrls = (fileUrls: unknown): unknown => {
  if (!Array.isArray(fileUrls)) {
    return fileUrls;
  }

  return fileUrls.map((fileUrl) => resolveManagedFileUrl(fileUrl));
};

export const resolveManagedFileUrlRecord = (value: unknown): unknown => {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return value;
  }

  return Object.fromEntries(
    Object.entries(value).map(([key, entryValue]) => [key, resolveManagedFileUrl(entryValue)]),
  );
};

export const resolveManagedFileUrlRecords = (value: unknown): unknown => {
  if (!Array.isArray(value)) {
    return value;
  }

  return value.map((entry) => resolveManagedFileUrlRecord(entry));
};
