import { promises as fs } from "fs";
import { randomUUID } from "crypto";
import { Attachment, AttachmentPartition } from "../../attachments/data/entities.js";
import { buildAttachmentFileUrl } from "../../attachments/lib/imageUrls.js";
import { ensureDefaultPartitions } from "../../attachments/lib/partitions.js";
import { resolveAttachmentAbsolutePath, storePartitionFile } from "../../attachments/lib/storage.js";
const SYNC_EXCEL_ATTACHMENT_ENTITY_ID = "sync_excel:upload";
const SYNC_EXCEL_PARTITION_CODE = "privateAttachments";
async function createSyncExcelUploadAttachment(input) {
  await ensureDefaultPartitions(input.em);
  const partition = await input.em.findOne(AttachmentPartition, { code: SYNC_EXCEL_PARTITION_CODE });
  if (!partition) {
    throw new Error("Storage partition is not configured.");
  }
  const stored = await storePartitionFile({
    partitionCode: partition.code,
    orgId: input.organizationId,
    tenantId: input.tenantId,
    fileName: input.fileName,
    buffer: input.buffer
  });
  const attachmentId = randomUUID();
  const attachment = input.em.create(Attachment, {
    id: attachmentId,
    entityId: SYNC_EXCEL_ATTACHMENT_ENTITY_ID,
    recordId: input.uploadId,
    organizationId: input.organizationId,
    tenantId: input.tenantId,
    partitionCode: partition.code,
    fileName: input.fileName,
    mimeType: input.mimeType,
    fileSize: input.buffer.length,
    storageDriver: partition.storageDriver || "local",
    storagePath: stored.storagePath,
    url: buildAttachmentFileUrl(attachmentId),
    storageMetadata: {
      module: "sync_excel",
      temporary: true,
      uploadId: input.uploadId
    }
  });
  input.em.persist(attachment);
  await input.em.flush();
  return attachment;
}
async function readSyncExcelUploadBuffer(attachment) {
  const inlineCsvBase64 = attachment.storageMetadata?.inlineCsvBase64;
  const absolutePath = resolveAttachmentAbsolutePath(
    attachment.partitionCode,
    attachment.storagePath,
    attachment.storageDriver
  );
  try {
    return await fs.readFile(absolutePath);
  } catch (error) {
    if (typeof inlineCsvBase64 === "string" && inlineCsvBase64.length > 0) {
      return Buffer.from(inlineCsvBase64, "base64");
    }
    throw error;
  }
}
export {
  createSyncExcelUploadAttachment,
  readSyncExcelUploadBuffer
};
//# sourceMappingURL=upload-storage.js.map
