import { Router } from 'express';
import path from 'path';
import os from 'os';
import fs from 'fs';

const router = Router();

router.get('/:filename', (req, res) => {
    const { filename } = req.params;
    // Sanitize filename to prevent directory traversal
    const safeFilename = path.basename(filename);

    // Path in tmp dir
    const filePath = path.join(os.tmpdir(), 'uploads', safeFilename);
    const localPath = path.join(process.cwd(), 'uploads', safeFilename);

    // Try serving from tmp first (serverless), then local (dev)
    if (fs.existsSync(filePath)) {
        res.sendFile(filePath);
    } else if (fs.existsSync(localPath)) {
        res.sendFile(localPath);
    } else {
        res.status(404).send('File not found');
    }
});

export default router;
