/**
 * Handler for fs_write messages.
 * Writes file content within a project with size validation and path security.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { writeFile, PathEscapeError, ContentTooLargeError } from "../services/filesystem.js";
import { logger } from "../utils/logger.js";
export async function handleFsWrite(message, send) {
    const msg = message;
    const { requestId, sessionId, payload } = msg;
    const { path: relativePath, content, createDirs } = payload;
    // Resolve project from sessionId (which is the projectId)
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "fs_write_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    try {
        const result = await writeFile(project.path, relativePath, content, createDirs ?? true);
        send({
            type: "fs_write_response",
            requestId,
            payload: {
                path: result.path,
                size: result.size,
                mtime: result.mtime,
            },
        });
    }
    catch (err) {
        if (err instanceof PathEscapeError) {
            send({
                type: "fs_write_response",
                requestId,
                error: {
                    code: ErrorCode.OUTSIDE_PROJECT_ROOT,
                    message: "Path escapes project directory",
                },
            });
            return;
        }
        if (err instanceof ContentTooLargeError) {
            send({
                type: "fs_write_response",
                requestId,
                error: {
                    code: ErrorCode.FILE_TOO_LARGE,
                    message: "Content exceeds 1MB limit",
                    details: { size: err.size, limit: err.limit },
                },
            });
            return;
        }
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`fs_write error: ${errorMessage}`);
        send({
            type: "fs_write_response",
            requestId,
            error: {
                code: ErrorCode.UNKNOWN_ERROR,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=fs-write.js.map