import { unlink } from 'fs/promises';
import { join } from 'path';
import { getUploadRoot } from './upload-paths';

const UPLOAD_URL_PREFIX = '/uploads/';

/** 按 `/uploads/{category}/{filename}` 删除磁盘文件；路径非法或文件不存在时静默跳过 */
export async function deleteUploadFileByUrl(url: string): Promise<void> {
  if (!url?.startsWith(UPLOAD_URL_PREFIX)) return;
  const relative = url.slice(UPLOAD_URL_PREFIX.length);
  if (!relative || relative.includes('..') || relative.includes('\\')) return;
  const root = getUploadRoot();
  try {
    await unlink(join(root, relative));
  } catch {
    /* already removed */
  }
}
