import fs from 'fs';
import path from 'path';

const UPLOADS_DIR = path.resolve(__dirname, '../../uploads');

function ensureUploadsDir(): void {
  if (!fs.existsSync(UPLOADS_DIR)) {
    fs.mkdirSync(UPLOADS_DIR, { recursive: true });
  }
}

// Stores a binary upload on disk and returns a *relative* path. The
// `rewriteUploadUrlsMiddleware` in server.ts turns these into absolute URLs
// at response time, derived from each incoming request, so the DB never has
// to track which host wrote the row. The 4th positional arg is accepted but
// ignored — kept for backwards compatibility with callers that still pass
// the request through.
export async function saveUpload(
  buffer: Buffer,
  key: string,
  _contentType: string,
  _req?: unknown,
): Promise<string> {
  ensureUploadsDir();

  const filePath = path.join(UPLOADS_DIR, key);
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  fs.writeFileSync(filePath, buffer);

  return `/uploads/${key}`;
}
