import 'server-only'
import fs from 'fs'
import path from 'path'

function storageRoot(): string {
  return process.env.DATAROOM_PATH || '/data/dataroom'
}

export function adminDocDir(documentId: string): string {
  return path.join(storageRoot(), 'admin', documentId)
}

export function investorUploadDir(investorId: string, uploadId: string): string {
  return path.join(storageRoot(), 'investors', investorId, uploadId)
}

export async function ensureDir(dir: string): Promise<void> {
  await fs.promises.mkdir(dir, { recursive: true })
}

export async function saveFile(dir: string, filename: string, buffer: Buffer): Promise<string> {
  await ensureDir(dir)
  const filePath = path.join(dir, filename)
  await fs.promises.writeFile(filePath, buffer)
  return filePath
}

export async function removeDir(dir: string): Promise<void> {
  await fs.promises.rm(dir, { recursive: true, force: true })
}

export async function streamFile(filePath: string): Promise<{ stream: ReadableStream; size: number }> {
  const stat = await fs.promises.stat(filePath)
  const nodeStream = fs.createReadStream(filePath)
  const stream = new ReadableStream({
    start(controller) {
      nodeStream.on('data', (chunk) => controller.enqueue(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))
      nodeStream.on('end', () => controller.close())
      nodeStream.on('error', (err) => controller.error(err))
    },
    cancel() { nodeStream.destroy() },
  })
  return { stream, size: stat.size }
}

export function safeName(original: string): string {
  return original.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 200)
}
