<?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;

/**
 * Elementor builder detection and field selection.
 */
final class ElementorBuilder implements BuilderInterface, UsageContainerCapableInterface
{
    /**
     * Return builder key.
     *
     * @return string
     */
    public function key(): string
    {
        return 'elementor';
    }

    /**
     * Detect Elementor 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
    {
        $postId = (int) $post->ID;
        $signals = [];

        if (metadata_exists('post', $postId, '_elementor_data')) {
            $signals[] = '_elementor_data';
        }

        if (metadata_exists('post', $postId, '_elementor_edit_mode')) {
            $signals[] = '_elementor_edit_mode';
        }

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

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

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

        return [
            new BuilderUsageHint(
                array_merge(ContentVisibility::getViewablePublicPostTypes(), ['elementor_component', 'elementor_library']),
                [
                    ['type' => 'post_meta', 'key' => '_elementor_data'],
                ],
                [
                    ['type' => 'meta_exists', 'key' => '_elementor_data'],
                ]
            ),
        ];
    }
}
