/**
 * Handler for project_create messages.
 * Validates the path, creates the project in SQLite, and sends project_added to the gateway.
 */
import { basename } from "node:path";
import { ErrorCode } from "@pocketcoder/shared/constants";
import { createProject, getProjectByPath } from "../db/repositories/projects.js";
import { validateProjectPath } from "../utils/validate-project-path.js";
import { sendProjectAdded } from "../gateway/messages/project-sync.js";
import { logger } from "../utils/logger.js";
/** The gateway client instance, set via setProjectCreateGatewayClient(). */
let _gatewayClient = null;
/** Callback to start a file watcher for a new project. */
let _startWatcher = null;
/**
 * Provide the gateway client to the handler.
 * Must be called during daemon startup before messages arrive.
 */
export function setProjectCreateGatewayClient(client) {
    _gatewayClient = client;
}
/**
 * Provide a callback to start a file watcher for a newly created project.
 * Must be called during daemon startup.
 */
export function setProjectCreateStartWatcher(startWatcher) {
    _startWatcher = startWatcher;
}
export async function handleProjectCreate(message, send) {
    const msg = message;
    const { requestId, payload } = msg;
    if (!payload?.path) {
        send({
            type: "project_create_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: "Missing required field: path",
            },
        });
        return;
    }
    try {
        // Validate the path exists and is a directory
        const fullPath = await validateProjectPath(payload.path);
        // Check if already registered
        const existing = getProjectByPath(fullPath);
        if (existing) {
            send({
                type: "project_create_response",
                requestId,
                error: {
                    code: ErrorCode.PROJECT_ALREADY_EXISTS,
                    message: `Project already registered: ${existing.name} (${existing.project_id})`,
                },
            });
            return;
        }
        // Create the project
        const name = basename(fullPath);
        const project = createProject(name, fullPath);
        logger.info(`Project created via tunnel: ${project.name} (${project.project_id})`);
        // Start file watcher for this project (if callback provided)
        if (_startWatcher) {
            _startWatcher(project.project_id, project.path);
        }
        // Send project_added to gateway (if connected)
        if (_gatewayClient) {
            sendProjectAdded(_gatewayClient, {
                projectId: project.project_id,
                name: project.name,
                path: project.path,
            });
        }
        send({
            type: "project_create_response",
            requestId,
            payload: {
                project: {
                    projectId: project.project_id,
                    name: project.name,
                    path: project.path,
                },
            },
        });
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`project_create error: ${errorMessage}`);
        send({
            type: "project_create_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_PATH,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=project-create.js.map