import "server-only";

import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";

import { env } from "@/lib/env";
import { STORAGE_KEY_PATTERN, type StorageDriver } from "@/lib/storage";

export function localStorageRoot() {
  // Resolved at runtime; keep the bundler from tracing the whole project into the build.
  return path.resolve(/* turbopackIgnore: true */ process.cwd(), env().STORAGE_LOCAL_DIR);
}

/** Resolves a key inside the storage root, refusing anything that could escape it. */
export function resolveLocalPath(key: string) {
  if (!STORAGE_KEY_PATTERN.test(key)) return null;
  const root = localStorageRoot();
  const filePath = path.resolve(/* turbopackIgnore: true */ root, key);
  return filePath.startsWith(root + path.sep) ? filePath : null;
}

export function createLocalStorage(): StorageDriver {
  return {
    async put(key, body) {
      const filePath = resolveLocalPath(key);
      if (!filePath) throw new Error(`Invalid storage key: ${key}`);
      await mkdir(path.dirname(filePath), { recursive: true });
      await writeFile(filePath, body, { flag: "wx" });
      return { url: `/uploads/${key}` };
    },
    async delete(key) {
      const filePath = resolveLocalPath(key);
      if (filePath) await rm(filePath, { force: true });
    },
  };
}

export async function readLocalFile(key: string) {
  const filePath = resolveLocalPath(key);
  if (!filePath) return null;
  try {
    return await readFile(/* turbopackIgnore: true */ filePath);
  } catch {
    return null;
  }
}
