const fs = require("fs");
const path = require("path");

require("dotenv").config();

const configuredPrivateDirectory =
  process.env.PRIVATE_UPLOAD_DIRECTORY ||
  path.join(
    __dirname,
    "..",
    "private_uploads"
  );

const privateUploadDirectory =
  path.resolve(
    configuredPrivateDirectory
  );

fs.mkdirSync(
  privateUploadDirectory,
  {
    recursive: true
  }
);

const resolvePrivateFile = (
  relativeStoragePath
) => {
  if (!relativeStoragePath) {
    throw new Error(
      "A document storage path is required."
    );
  }

  const absolutePath =
    path.resolve(
      privateUploadDirectory,
      relativeStoragePath
    );

  const permittedPrefix =
    `${privateUploadDirectory}${path.sep}`;

  if (
    absolutePath !==
      privateUploadDirectory &&
    !absolutePath.startsWith(
      permittedPrefix
    )
  ) {
    throw new Error(
      "Invalid document storage path."
    );
  }

  return absolutePath;
};

module.exports = {
  privateUploadDirectory,
  resolvePrivateFile
};