/* Onde mora o arquivo de uma foto de produto. Sem banco, para o teste rodar sozinho. */

const MARCA_PUBLICA = "/storage/v1/object/public/";

/** O depósito e o caminho do arquivo de uma foto, pelo caminho guardado ou pelo endereço público. */
export function arquivoDaFoto(foto: { url?: string | null; path?: string | null; image_url?: string | null }): { bucket: string; filePath: string } | null {
  if (foto.path) return { bucket: "products", filePath: foto.path };
  const endereco = foto.image_url || foto.url;
  if (!endereco) return null;
  try {
    const url = new URL(endereco);
    const indice = url.pathname.indexOf(MARCA_PUBLICA);
    /* Foto de fora (link de outro site, importação antiga): não é arquivo nosso. */
    if (indice < 0) return null;
    const [bucket, ...resto] = decodeURIComponent(url.pathname.slice(indice + MARCA_PUBLICA.length)).split("/");
    if (!bucket || resto.length === 0) return null;
    return { bucket, filePath: resto.join("/") };
  } catch {
    return null;
  }
}
