import { createClient } from "@/lib/supabase/server"; import { PFLICHT_FOTO_POSITIONEN } from "./foto-positionen"; export type AuftragFoto = { position: string; label: string; url: string; downloadUrl: string; }; export type FotoZeile = { position: string; storage_path: string; uploaded_at: string; }; export function sortiereUndBeschrifteFotos(fotos: FotoZeile[]): (FotoZeile & { label: string })[] { const pflichtFotos = PFLICHT_FOTO_POSITIONEN.map((position) => fotos.find((foto) => foto.position === position) ).filter((foto): foto is FotoZeile => foto !== undefined); const schadenFotos = fotos .filter((foto) => foto.position === "schaden") .sort((a, b) => a.uploaded_at.localeCompare(b.uploaded_at)); const beschriftetePflichtFotos = pflichtFotos.map((foto) => ({ ...foto, label: foto.position.replaceAll("_", " "), })); const beschrifteteSchadenFotos = schadenFotos.map((foto, index) => ({ ...foto, label: schadenFotos.length > 1 ? `Schaden ${index + 1}` : "Schaden", })); return [...beschriftetePflichtFotos, ...beschrifteteSchadenFotos]; } export async function loadAuftragFotos(auftragId: string): Promise { const supabase = await createClient(); const { data } = await supabase .from("auftrag_fotos") .select("position, storage_path, uploaded_at") .eq("auftrag_id", auftragId); if (!data || data.length === 0) { return []; } const sortiert = sortiereUndBeschrifteFotos(data); const publicUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!; const fotos = await Promise.all( sortiert.map(async (foto): Promise => { const { data: signiert } = await supabase.storage .from("auftrag-fotos") .createSignedUrl(foto.storage_path, 3600); if (!signiert) { return null; } const geparst = new URL(signiert.signedUrl); const url = `${publicUrl}${geparst.pathname}${geparst.search}`; const dateiname = foto.storage_path.split("/").pop() ?? `${foto.position}.jpg`; const downloadUrl = `${url}&download=${encodeURIComponent(dateiname)}`; return { position: foto.position, label: foto.label, url, downloadUrl }; }) ); return fotos.filter((foto): foto is AuftragFoto => foto !== null); }