/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { execFile } from 'node:child_process';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
import { Hono } from 'hono';
import { getWorkspaceCwd } from '../middleware/workspace.js';
const execFileAsync = promisify(execFile);
export function deployRoute(cwd) {
    const app = new Hono();
    app.post('/source', async (c) => {
        const dir = getWorkspaceCwd(c, cwd);
        const body = await c.req.json();
        if (!body.path || typeof body.path !== 'string') {
            return c.json({ error: 'Missing path field' }, 400);
        }
        const resolved = resolve(dir, body.path);
        if (!resolved.startsWith(dir + '/') && resolved !== dir) {
            return c.json({ error: 'Forbidden: path traversal detected' }, 403);
        }
        if (!existsSync(resolved)) {
            return c.json({ error: 'Source path not found' }, 404);
        }
        try {
            const { stdout, stderr } = await execFileAsync('sf', ['project', 'deploy', 'start', '--source-dir', resolved], {
                cwd: dir,
                timeout: 120_000,
            });
            const output = (stdout + '\n' + stderr).trim();
            return c.json({ ok: true, output });
        }
        catch (err) {
            const execErr = err;
            const output = ((execErr.stdout ?? '') + '\n' + (execErr.stderr ?? '')).trim();
            const error = execErr.message ?? 'Deploy failed';
            return c.json({ error, output }, 500);
        }
    });
    return app;
}
//# sourceMappingURL=deploy.js.map