const isFullUrl = (value: string) => /^https?:\/\//i.test(value);

/**
 * Builds a public S3 URL from a stored key. Existing rows saved before this
 * change already contain full URLs — those are passed through unchanged so
 * old data keeps working.
 */
export const toImageUrl = (key?: string | null): string => {
  if (!key) return "";
  if (isFullUrl(key)) return key;

  const base = (process.env.AWS_S3_BASE_URL || "").replace(/\/+$/, "");
  return `${base}/${key.replace(/^\/+/, "")}`;
};

export const toImageUrls = (keys?: (string | null | undefined)[]): string[] =>
  (keys || []).map((key) => toImageUrl(key)).filter(Boolean);
