<?php

namespace PloverCRM\Modules\ContactEnrichment\Endpoints;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\ContactEnrichment\Services\PostCreateJobManager;
use WP_REST_Request;

/**
 * Internal callback endpoint used by the worker queue consumer.
 */
class PostCreateJobCallbackEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/internal/post-create-jobs/run';
    }

    public function getMethod(): string
    {
        return 'POST';
    }

    public function checkPermission(WP_REST_Request $request)
    {
        return true;
    }

    public function handle(WP_REST_Request $request)
    {
        $jobId = sanitize_text_field((string) $request->get_param('job_id'));
        $dispatchToken = sanitize_text_field((string) $request->get_header('X-PloverCRM-Job-Token'));

        if ($jobId === '' || $dispatchToken === '') {
            return $this->error('job_id and X-PloverCRM-Job-Token are required.', 400, 'missing_job_auth');
        }

        try {
            $result = (new PostCreateJobManager($this->container))->run($jobId, $dispatchToken);

            return $this->success($result);
        } catch (\Throwable $throwable) {
            return $this->error(
                'Failed to run the background lead job.',
                500,
                [
                    'code' => 'background_job_run_failed',
                    'message' => $throwable->getMessage(),
                ]
            );
        }
    }
}
