"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFilesRouter = createFilesRouter;
const path_1 = __importDefault(require("path"));
const express_1 = require("express");
const validation_1 = require("../../api/rest/validation");
function createFilesRouter() {
    const router = (0, express_1.Router)({ mergeParams: true });
    function getProject(req) {
        return req.project;
    }
    // List all files
    router.get('/', (0, validation_1.validateQuery)(validation_1.fileListSchema), (req, res, next) => {
        try {
            const p = getProject(req);
            const q = req.validatedQuery;
            const { results: files, total } = p.fileIndexManager.listAllFiles(q);
            res.json({ results: files, total });
        }
        catch (err) {
            next(err);
        }
    });
    // Search files
    router.get('/search', (0, validation_1.validateQuery)(validation_1.fileSearchSchema), async (req, res, next) => {
        try {
            const p = getProject(req);
            const q = req.validatedQuery;
            const results = await p.fileIndexManager.search(q.q, {
                topK: q.topK,
                minScore: q.minScore,
            });
            res.json({ results });
        }
        catch (err) {
            next(err);
        }
    });
    // Get file info
    router.get('/info', (req, res, next) => {
        try {
            const p = getProject(req);
            const filePath = req.query.path;
            if (!filePath)
                return res.status(400).json({ error: 'path query parameter required' });
            // Prevent path traversal
            const normalized = path_1.default.normalize(filePath);
            if (normalized.startsWith('..') || path_1.default.isAbsolute(normalized)) {
                return res.status(400).json({ error: 'Invalid path' });
            }
            const info = p.fileIndexManager.getFileInfo(normalized);
            if (!info)
                return res.status(404).json({ error: 'File not found' });
            res.json(info);
        }
        catch (err) {
            next(err);
        }
    });
    return router;
}
