<?php

namespace BitApps\PiPro\HTTP\Controllers;

use BitApps\Pi\Helpers\Parser;
use BitApps\Pi\Model\Flow;
use BitApps\Pi\Model\FlowNode;
use BitApps\Pi\src\Flow\FlowExecutor;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Request\Request;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Response;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

/**
 * Controller for running flows with existing data.
 *
 * This controller handles the execution of flows using previously captured data.
 */
class FlowRunController
{
    /**
     * Get the node data for a specific node ID.
     *
     * @return Response Success response with node data or error response
     */
    public function flowRunWithExistingData(Request $request)
    {
        $validatedData = $request->validate(
            [
                'flow_id' => ['required', 'integer'],
            ]
        );

        $flowId = $validatedData['flow_id'];

        $flow = Flow::select(['id', 'title', 'settings', 'is_active', 'map', 'trigger_type', 'listener_type', 'is_hook_capture'])->where('id', $flowId)->first();

        if (!$flow) {
            return Response::error('Flow does not exist');
        }

        $firstNodeId = $flowId . '-1';

        $nodeData = FlowNode::select(['variables'])->where('node_id', $firstNodeId)->first();

        if (empty($nodeData)) {
            return Response::error('Node not found', 404);
        }

        if (empty($nodeData['variables'])) {
            return Response::error('No existing response found. You have to capture a response first to use this feature', 404);
        }

        $triggerData = Parser::parseArrayStructure($nodeData['variables']);

        FlowExecutor::execute($flow, $triggerData);

        return Response::success($triggerData);
    }
}
