"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEmbedRouter = createEmbedRouter;
const crypto_1 = __importDefault(require("crypto"));
const express_1 = require("express");
const zod_1 = require("zod");
const embedder_1 = require("../../lib/embedder");
const embedding_codec_1 = require("../../lib/embedding-codec");
/**
 * Create an Express router for the embedding API.
 * POST /api/embed — embed texts using the server's embedding model.
 *
 * Accepts `model` parameter: "default" (general model) or "code" (code-optimized model).
 */
function createEmbedRouter(apiConfig, modelNames) {
    const router = (0, express_1.Router)();
    const embedRequestSchema = zod_1.z.object({
        texts: zod_1.z.array(zod_1.z.string().max(apiConfig.maxTextChars)).min(1).max(apiConfig.maxTexts),
        format: zod_1.z.enum(['json', 'base64']).optional().default('json'),
        model: zod_1.z.enum(['default', 'code']).optional().default('default'),
    });
    router.post('/', async (req, res, next) => {
        try {
            // Auth: check embeddingApi.apiKey (separate from user apiKey)
            if (apiConfig.apiKey) {
                const auth = req.headers.authorization;
                if (!auth?.startsWith('Bearer ')) {
                    return res.status(401).json({ error: 'Invalid embedding API key' });
                }
                const provided = Buffer.from(auth.slice(7));
                const expected = Buffer.from(apiConfig.apiKey);
                if (provided.length !== expected.length || !crypto_1.default.timingSafeEqual(provided, expected)) {
                    return res.status(401).json({ error: 'Invalid embedding API key' });
                }
            }
            const parsed = embedRequestSchema.parse(req.body);
            const inputs = parsed.texts.map(text => ({ title: text, content: '' }));
            const modelName = modelNames[parsed.model];
            const embeddings = await (0, embedder_1.embedBatch)(inputs, modelName);
            if (parsed.format === 'base64') {
                res.json({ embeddings: embeddings.map(e => (0, embedding_codec_1.float32ToBase64)(e)), format: 'base64' });
            }
            else {
                res.json({ embeddings });
            }
        }
        catch (err) {
            if (err?.name === 'ZodError') {
                return res.status(400).json({ error: 'Validation error' });
            }
            next(err);
        }
    });
    return router;
}
