import { promises as fs } from "fs";
import path from "path";
import { randomUUID } from "crypto";
import { resolvePartitionRoot } from "../storage.js";
import { resolveContainedPath } from "../pathContainment.js";
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";
}
class LocalStorageDriver {
  constructor() {
    this.key = "local";
  }
  async store(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, "/")
    };
  }
  async read(partitionCode, storagePath) {
    const absolutePath = this.resolveAbsolutePath(partitionCode, storagePath);
    const buffer = await fs.readFile(absolutePath);
    return { buffer };
  }
  async delete(partitionCode, storagePath) {
    const absolutePath = this.resolveAbsolutePath(partitionCode, storagePath);
    try {
      await fs.unlink(absolutePath);
    } catch {
    }
  }
  async toLocalPath(partitionCode, storagePath) {
    const filePath = this.resolveAbsolutePath(partitionCode, storagePath);
    return {
      filePath,
      cleanup: async () => {
      }
    };
  }
  resolveAbsolutePath(partitionCode, storagePath) {
    const root = resolvePartitionRoot(partitionCode);
    return resolveContainedPath(root, storagePath);
  }
}
export {
  LocalStorageDriver
};
//# sourceMappingURL=localDriver.js.map
