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

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

    /**
     * Detect Beaver Builder 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, '_fl_builder_data')) {
            $signals[] = '_fl_builder_data';
        }

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

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

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

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

        return [
            new BuilderUsageHint(
                array_merge(ContentVisibility::getViewablePublicPostTypes(), ['fl-builder-template']),
                [
                    ['type' => 'post_meta', 'key' => '_fl_builder_data'],
                    ['type' => 'post_meta', 'key' => '_fl_builder_data_settings'],
                ],
                [
                    ['type' => 'meta_exists', 'key' => '_fl_builder_data'],
                    ['type' => 'meta_exists', 'key' => '_fl_builder_data_settings'],
                ]
            ),
        ];
    }
}
