import { unlink } from "fs/promises";
import { join, resolve } from "path";
import { isUploadAssetPath } from "./image-url";

function resolveUploadsRoot(): string {
  return resolve(process.cwd(), "public", "uploads");
}

/** Supprime un asset local /uploads/... si présent, sans lever d'erreur si absent. */
export async function deleteUploadAssetIfAny(src: string | null | undefined) {
  if (!src) return;
  if (!isUploadAssetPath(src)) return;

  const rel = src.slice("/uploads/".length).trim();
  if (!rel || rel.includes("..")) return;

  const uploadsRoot = resolveUploadsRoot();
  const fullPath = resolve(join(uploadsRoot, rel));
  if (!fullPath.startsWith(uploadsRoot + "/")) return;

  try {
    await unlink(fullPath);
  } catch (e: unknown) {
    const code = (e as { code?: string })?.code;
    if (code !== "ENOENT") {
      throw e;
    }
  }
}

