// src/routes/api/cancel-process/+server.ts
import { json, type RequestHandler } from '@sveltejs/kit';
import { activeProcesses } from '$lib/server/processes';

/**
 * 진행 중인 프로세스를 취소하는 API 핸들러
 */
export const POST: RequestHandler = async ({ request }) => {
    try {
        const { processId } = await request.json();

        if (!processId) {
            return json({ success: false, error: 'Process ID is required' }, { status: 400 });
        }

        const processToKill = activeProcesses.get(processId);

        if (processToKill) {
            console.log(`[${processId}] Received cancellation request. Killing process.`);
            // SIGKILL 신호를 보내 프로세스를 강제 종료합니다.
            processToKill.kill('SIGKILL'); 
            activeProcesses.delete(processId); // 맵에서 프로세스를 제거합니다.
            return json({ success: true, message: `Process ${processId} was cancelled.` });
        } else {
            console.warn(`[${processId}] Attempted to cancel a process that does not exist or has already completed.`);
            return json({ success: false, error: 'Process not found or already completed.' }, { status: 404 });
        }
    } catch (error) {
        console.error('Error cancelling process:', error);
        return json({ success: false, error: 'Internal server error' }, { status: 500 });
    }
};
