/**
 * Handler for project_delete messages.
 * Validates the project exists, deletes it from SQLite, stops the file watcher,
 * and sends project_removed to the gateway.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject, deleteProject } from "../db/repositories/projects.js";
import { sendProjectRemoved } from "../gateway/messages/project-sync.js";
import { logger } from "../utils/logger.js";
/** The gateway client instance, set via setProjectDeleteGatewayClient(). */
let _gatewayClient = null;
/** Callback to stop the file watcher for a project. */
let _stopWatcher = null;
/**
 * Provide the gateway client to the handler.
 * Must be called during daemon startup before messages arrive.
 */
export function setProjectDeleteGatewayClient(client) {
    _gatewayClient = client;
}
/**
 * Provide a callback to stop the file watcher for a given project.
 * Must be called during daemon startup.
 */
export function setProjectDeleteStopWatcher(stopWatcher) {
    _stopWatcher = stopWatcher;
}
export async function handleProjectDelete(message, send) {
    const msg = message;
    const { requestId, payload } = msg;
    if (!payload?.projectId) {
        send({
            type: "project_delete_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: "Missing required field: projectId",
            },
        });
        return;
    }
    const { projectId } = payload;
    // Check project exists
    const project = getProject(projectId);
    if (!project) {
        send({
            type: "project_delete_response",
            requestId,
            error: {
                code: ErrorCode.PROJECT_NOT_FOUND,
                message: `Project not found: ${projectId}`,
            },
        });
        return;
    }
    try {
        // Stop file watcher for this project (if callback provided)
        if (_stopWatcher) {
            await _stopWatcher(projectId);
        }
        // Delete from database (cascades to fs_state, etc.)
        deleteProject(projectId);
        logger.info(`Project deleted via tunnel: ${project.name} (${projectId})`);
        // Send project_removed to gateway (if connected)
        if (_gatewayClient) {
            sendProjectRemoved(_gatewayClient, projectId);
        }
        send({
            type: "project_delete_response",
            requestId,
            payload: {
                success: true,
            },
        });
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`project_delete error: ${errorMessage}`);
        send({
            type: "project_delete_response",
            requestId,
            error: {
                code: ErrorCode.UNKNOWN_ERROR,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=project-delete.js.map