import { promises as fs } from "fs";
import path from "path";
import { randomUUID } from "crypto";
import { resolvePartitionEnvKey } from "./partitionEnv.js";
import { resolveContainedPath, resolveLegacyPublicRoot } from "./pathContainment.js";
function resolvePartitionRoot(code) {
  const envKey = resolvePartitionEnvKey(code);
  const envPath = process.env[envKey];
  if (envPath && envPath.trim().length > 0) {
    return path.resolve(envPath);
  }
  return path.join(process.cwd(), "storage", "attachments", code);
}
function sanitizeFileName(fileName) {
  if (!fileName) return "file";
  return fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function resolveOrgSegment(orgId) {
  if (typeof orgId === "string" && orgId.trim().length > 0) return `org_${orgId}`;
  return "org_shared";
}
function resolveTenantSegment(tenantId) {
  if (typeof tenantId === "string" && tenantId.trim().length > 0) return `tenant_${tenantId}`;
  return "tenant_shared";
}
async function storePartitionFile(payload) {
  const root = resolvePartitionRoot(payload.partitionCode);
  const orgSegment = resolveOrgSegment(payload.orgId ?? null);
  const tenantSegment = resolveTenantSegment(payload.tenantId ?? null);
  const safeName = sanitizeFileName(payload.fileName || "file");
  const uniqueSuffix = randomUUID().replace(/-/g, "").slice(0, 12);
  const storedName = `${Date.now()}_${uniqueSuffix}_${safeName}`;
  const relativePath = path.join(orgSegment, tenantSegment, storedName);
  const absolutePath = path.join(root, relativePath);
  await fs.mkdir(path.dirname(absolutePath), { recursive: true });
  await fs.writeFile(absolutePath, payload.buffer);
  return {
    storagePath: relativePath.replace(/\\/g, "/"),
    absolutePath,
    fileName: storedName
  };
}
function resolveAttachmentAbsolutePath(partitionCode, storagePath, storageDriver) {
  if (storageDriver === "legacyPublic") {
    return resolveContainedPath(process.cwd(), storagePath, resolveLegacyPublicRoot());
  }
  const root = resolvePartitionRoot(partitionCode);
  return resolveContainedPath(root, storagePath);
}
async function deletePartitionFile(partitionCode, storagePath, storageDriver) {
  const absolutePath = resolveAttachmentAbsolutePath(partitionCode, storagePath, storageDriver);
  try {
    await fs.unlink(absolutePath);
  } catch {
  }
}
export {
  deletePartitionFile,
  resolveAttachmentAbsolutePath,
  resolvePartitionRoot,
  storePartitionFile
};
//# sourceMappingURL=storage.js.map
