<?php

namespace GriffinForms\Includes\Pipelines\Accounts;

class JobProcessor
{
    protected $state_store;
    protected $executor;

    public function __construct()
    {
        $this->state_store = new ActionStateStore();
        $this->executor = new LifecycleExecutor();
    }

    public function process(array $job, array $payload): void
    {
        $submission_id = isset($job['submission_id']) ? (int) $job['submission_id'] : 0;
        $action_id = isset($payload['action_id']) ? sanitize_key((string) $payload['action_id']) : '';

        if ($submission_id <= 0 || $action_id === '') {
            throw new \RuntimeException('WordPress account job payload is missing submission or action context.');
        }

        $this->state_store->updateAction($submission_id, $action_id, [
            'status' => Contract::STATUS_PROCESSING,
            'status_reason' => '',
            'status_message' => 'WordPress account job is processing.',
        ]);

        $result = $this->executor->executeImmediateAction($submission_id, $action_id, $payload, 'job');
        if (is_wp_error($result)) {
            throw new \RuntimeException($result->get_error_message());
        }
    }
}
