/**
 * 属性文件 API 路由
 *
 * 提供属性文件的读取和写入功能
 */
import { Router } from 'express';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { validateToken } from '../middleware/auth.js';
import { resolvePropertiesTargetPath } from '../utils/path-utils.js';
export const propertiesRouter = Router();
/**
 * 读取属性文件
 * POST /runtime/read-properties
 */
propertiesRouter.post('/read-properties', validateToken, async (req, res) => {
    const { workspacePath, propertiesPath } = req.body || {};
    try {
        const { normalizedWorkspace, resolvedTarget } = resolvePropertiesTargetPath(workspacePath, propertiesPath);
        let content = '';
        let exists = true;
        try {
            content = await fs.readFile(resolvedTarget, 'utf-8');
        }
        catch (error) {
            const err = error;
            if (err?.code === 'ENOENT') {
                exists = false;
            }
            else {
                throw error;
            }
        }
        res.json({
            ok: true,
            workspacePath: normalizedWorkspace,
            filePath: resolvedTarget,
            exists,
            content,
        });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'read properties failed' });
    }
});
/**
 * 写入属性文件
 * POST /runtime/write-properties
 */
propertiesRouter.post('/write-properties', validateToken, async (req, res) => {
    const { workspacePath, propertiesPath, content } = req.body || {};
    if (!content || !String(content).trim()) {
        res.status(400).json({ error: 'content is required' });
        return;
    }
    try {
        const { normalizedWorkspace, resolvedTarget } = resolvePropertiesTargetPath(workspacePath, propertiesPath);
        const targetDir = path.dirname(resolvedTarget);
        await fs.mkdir(targetDir, { recursive: true });
        await fs.writeFile(resolvedTarget, String(content), 'utf-8');
        res.json({
            ok: true,
            workspacePath: normalizedWorkspace,
            filePath: resolvedTarget,
        });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'write properties failed' });
    }
});
