"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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 path_1 = __importDefault(require("path"));
const api = __importStar(require("../api/files"));
const storage_1 = require("../lib/storage");
const mime_1 = require("../lib/storage/mime");
const router = (0, express_1.Router)();
/**
 * GET /api/file-browser/browse
 * List files and directories at a given prefix.
 * Query: ?prefix=screenshots/&pageSize=100&continuationToken=...
 */
router.get('/browse', async (req, res) => {
    const result = await api.browseFiles({
        prefix: req.query.prefix,
        pageSize: req.query.pageSize ? parseInt(req.query.pageSize, 10) : undefined,
        continuationToken: req.query.continuationToken,
    });
    res.status(result.status).json(result.data ?? { error: result.error });
});
/**
 * GET /api/file-browser/metadata/*
 * Get metadata for a single file.
 */
router.get('/metadata/{*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;
    }
    const result = await api.getFileMetadata({ filePath });
    res.status(result.status).json(result.data ?? { error: result.error });
});
/**
 * POST /api/file-browser/signed-url
 * Generate a time-limited signed URL for sharing.
 * Body: { path, expiresIn } — expiresIn in seconds (3600, 21600, 86400, 604800, 2592000)
 */
router.post('/signed-url', async (req, res) => {
    const { path: filePath, expiresIn } = req.body;
    if (!filePath || !expiresIn) {
        res.status(400).json({ error: 'path and expiresIn are required' });
        return;
    }
    const result = await api.generateSignedUrl({
        filePath,
        expiresIn: typeof expiresIn === 'number' ? expiresIn : parseInt(expiresIn, 10),
    });
    res.status(result.status).json(result.data ?? { error: result.error });
});
/**
 * DELETE /api/file-browser/delete/*
 * Permanently delete a file.
 */
router.delete('/delete/{*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;
    }
    const result = await api.deleteFile({ filePath });
    res.status(result.status).json(result.data ?? { error: result.error });
});
/**
 * GET /api/file-browser/download/*
 * Download a file with Content-Disposition: attachment.
 */
router.get('/download/{*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;
    }
    try {
        const stream = await (0, storage_1.getStorageBackend)().createReadStream(filePath);
        const fileName = path_1.default.basename(filePath);
        const contentType = (0, mime_1.mimeFromPath)(filePath);
        res.setHeader('Content-Type', contentType);
        res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
        stream.pipe(res);
    }
    catch {
        res.status(404).json({ error: 'File not found' });
    }
});
/**
 * POST /api/file-browser/upload
 * Upload a file to storage.
 * Query: ?path=images/photo.png (target path including filename)
 * Body: raw file bytes (Content-Type should match the file type)
 */
router.post('/upload', async (req, res) => {
    const targetPath = req.query.path;
    if (!targetPath) {
        res.status(400).json({ error: 'path query parameter required (e.g., ?path=images/photo.png)' });
        return;
    }
    // Collect raw body chunks
    const chunks = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', async () => {
        try {
            const buffer = Buffer.concat(chunks);
            if (buffer.length === 0) {
                res.status(400).json({ error: 'Empty file body' });
                return;
            }
            const result = await api.uploadFile({ path: targetPath, buffer });
            res.status(result.status).json(result.data ?? { error: result.error });
        }
        catch (err) {
            res.status(500).json({ error: err.message });
        }
    });
});
exports.default = router;
