import fs from "node:fs/promises";
import path from "node:path";
import { config } from "./config.js";

const invalidNamePattern = /[\\/:*?"<>|]/;

export function assertValidFolderName(name: string) {
  const trimmed = name.trim();
  if (!trimmed) {
    throw new Error("名称不能为空");
  }
  if (invalidNamePattern.test(trimmed)) {
    throw new Error('名称不能包含 \\ / : * ? " < > |');
  }
  if (trimmed === "." || trimmed === "..") {
    throw new Error("名称不合法");
  }
  return trimmed;
}

export function assertGlbFilename(filename: string) {
  if (path.extname(filename).toLowerCase() !== ".glb") {
    throw new Error("当前阶段只允许上传 .glb 模型");
  }
}

export function safeStoragePath(relativePath: string) {
  const fullPath = path.resolve(config.storageDir, relativePath);
  const root = path.resolve(config.storageDir);
  if (!fullPath.startsWith(root)) {
    throw new Error("文件路径不合法");
  }
  return fullPath;
}

export async function ensureDir(dirPath: string) {
  await fs.mkdir(dirPath, { recursive: true });
}

export async function removeIfExists(targetPath: string) {
  await fs.rm(targetPath, { recursive: true, force: true });
}

export function toStorageRelative(folderPath: string, filename: string) {
  return path.join("models", folderPath, filename);
}

export function toFolderStorageRelative(folderPath: string) {
  return path.join("models", folderPath);
}

export function normalizeModelName(filename: string) {
  return path.basename(filename, path.extname(filename)).trim();
}

