<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Integrations\Builders\Adapters;

use Ekesto\CacheInvalidator\BuilderUsageHint;
use Ekesto\CacheInvalidator\Integrations\Builders\BuilderInterface;
use Ekesto\CacheInvalidator\Integrations\Builders\UsageContainerCapableInterface;
use Ekesto\CacheInvalidator\ContentVisibility;

/**
 * WPBakery detection with content-only scanning.
 */
final class WPBakeryBuilder implements BuilderInterface, UsageContainerCapableInterface
{
    /**
     * Return builder key.
     *
     * @return string
     */
    public function key(): string
    {
        return 'wpbakery';
    }

    /**
     * Detect WPBakery usage for this post.
     *
     * @param \WP_Post $post Post object.
     * @return array{detected:bool,confidence:string,signals:string[]}
     */
    public function detect(\WP_Post $post): array
    {
        $content = (string) $post->post_content;
        $tokens = ['[vc_row', '[vc_column', '[vc_section', '[vc_row_inner'];
        $signals = [];

        foreach ($tokens as $token) {
            if (stripos($content, $token) !== false) {
                $signals[] = $token;
                break;
            }
        }

        return [
            'detected' => !empty($signals),
            'confidence' => !empty($signals) ? 'likely' : 'unknown',
            'signals' => $signals,
        ];
    }

    /**
     * Return extra fields to scan.
     *
     * @return string[]
     */
    public function additionalFieldsToScan(): array
    {
        return [];
    }

    /**
     * @param \WP_Post $entity
     * @return BuilderUsageHint[]
     */
    public function getUsageContainerIds(\WP_Post $entity): array
    {
        unset($entity);

        return [
            new BuilderUsageHint(
                ContentVisibility::getViewablePublicPostTypes(),
                [
                    ['type' => 'post_content'],
                ],
                [
                    ['type' => 'post_content_contains', 'value' => '[vc_'],
                ]
            ),
        ];
    }
}
