"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const storage_1 = require("../lib/storage");
const mime_1 = require("../lib/storage/mime");
const router = (0, express_1.Router)();
/**
 * GET /api/files/*
 * Serve files from managed file storage.
 * Requires a signed token (?token=<jwt>) for authenticated access.
 * Use POST /api/file-browser/signed-url to generate a token.
 */
router.get('/{*filePath}', async (req, res) => {
    const raw = req.params.filePath;
    const filePath = Array.isArray(raw) ? raw.join('/') : raw;
    if (!filePath) {
        res.status(400).json({ error: 'File path required' });
        return;
    }
    // Require signed token — no unauthenticated file access
    const token = req.query.token;
    if (!token) {
        res.status(401).json({ error: 'Signed token required. Use /api/file-browser/signed-url to generate one.' });
        return;
    }
    const secret = process.env.JWT_SECRET;
    if (!secret) {
        res.status(500).json({ error: 'Server not configured for signed URLs' });
        return;
    }
    try {
        const decoded = jsonwebtoken_1.default.verify(token, secret);
        if (decoded.purpose !== 'file-download' || decoded.filePath !== filePath.replace(/^\/+/, '')) {
            res.status(403).json({ error: 'Token does not match requested file' });
            return;
        }
    }
    catch {
        res.status(403).json({ error: 'Invalid or expired token' });
        return;
    }
    try {
        const stream = await (0, storage_1.getStorageBackend)().createReadStream(filePath);
        const contentType = (0, mime_1.mimeFromPath)(filePath);
        res.setHeader('Content-Type', contentType);
        res.setHeader('Cache-Control', 'public, max-age=300');
        stream.pipe(res);
    }
    catch {
        res.status(404).json({ error: 'File not found' });
    }
});
exports.default = router;
