"use strict";
// Routes for design token extraction and management
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTokenRouter = void 0;
const express_1 = require("express");
const DesignTokenService_1 = require("../services/DesignTokenService");
const TailwindConfigWriter_1 = require("../services/TailwindConfigWriter");
const CSSTokenWriter_1 = require("../services/CSSTokenWriter");
const TailwindCSSTokenAdapter_1 = require("../services/adapters/TailwindCSSTokenAdapter");
const logger_1 = require("../utils/logger");
const log = (0, logger_1.createLogger)('TokenRoutes');
const createTokenRouter = (projectPath, styleFramework, tailwindConfig) => {
    const router = (0, express_1.Router)();
    const tokenService = new DesignTokenService_1.DesignTokenService();
    const v3Writer = new TailwindConfigWriter_1.TailwindConfigWriter();
    const v4Writer = new CSSTokenWriter_1.CSSTokenWriter();
    const v4Detector = new TailwindCSSTokenAdapter_1.TailwindCSSTokenAdapter();
    /**
     * GET /api/tokens
     * Extracts and returns design tokens from the project
     */
    router.get('/tokens', async (req, res) => {
        try {
            log.info('Extracting design tokens');
            const result = tokenService.extractTokens(projectPath, styleFramework, tailwindConfig);
            if (!result) {
                // No tokens found
                const response = {
                    registry: {
                        colors: {},
                        spacing: {},
                        fontSize: {},
                        borderRadius: {},
                        boxShadow: {},
                        fontFamily: {},
                    },
                    framework: null,
                };
                res.json(response);
                return;
            }
            const response = {
                registry: result.registry,
                framework: result.framework,
            };
            log.info(`Returning ${result.framework} tokens`);
            res.json(response);
        }
        catch (error) {
            log.error('Failed to extract tokens:', error);
            res.status(500).json({
                error: 'Token extraction failed',
                details: error instanceof Error ? error.message : 'Unknown error',
            });
        }
    });
    /**
     * POST /api/tokens/update
     * Updates a token value in the Tailwind config file
     */
    router.post('/tokens/update', async (req, res) => {
        try {
            const request = req.body;
            if (!request.category || !request.path || request.value === undefined) {
                res.status(400).json({
                    success: false,
                    error: 'Missing required fields: category, path, value',
                });
                return;
            }
            log.info(`Updating token ${request.category}.${request.path} to "${request.value}"`);
            // Use v4 writer for projects with @theme blocks, v3 writer otherwise
            const isV4 = v4Detector.detect(projectPath);
            const writer = isV4 ? v4Writer : v3Writer;
            const result = await writer.updateToken(projectPath, request, tailwindConfig);
            if (result.success) {
                // Invalidate cache so next GET /tokens returns fresh data
                tokenService.invalidateCache(projectPath);
                res.json(result);
            }
            else {
                res.status(500).json(result);
            }
        }
        catch (error) {
            log.error('Failed to update token:', error);
            res.status(500).json({
                success: false,
                error: 'Token update failed',
                details: error instanceof Error ? error.message : 'Unknown error',
            });
        }
    });
    /**
     * POST /api/tokens/invalidate
     * Invalidates the token cache, forcing re-extraction on next request
     */
    router.post('/tokens/invalidate', async (req, res) => {
        try {
            tokenService.invalidateCache(projectPath);
            log.info('Token cache invalidated');
            res.json({ success: true });
        }
        catch (error) {
            log.error('Failed to invalidate token cache:', error);
            res.status(500).json({
                error: 'Cache invalidation failed',
                details: error instanceof Error ? error.message : 'Unknown error',
            });
        }
    });
    return router;
};
exports.createTokenRouter = createTokenRouter;
//# sourceMappingURL=tokens.js.map