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

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

    /**
     * Detect Divi 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;
        $raw = get_post_meta($postId, '_et_pb_use_builder', true);
        $isTruthy = !in_array(strtolower((string) $raw), ['', '0', 'false', 'off'], true);

        return [
            'detected' => $isTruthy,
            'confidence' => $isTruthy ? 'likely' : 'unknown',
            'signals' => $isTruthy ? ['_et_pb_use_builder'] : [],
        ];
    }

    /**
     * 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' => 'meta_exists', 'key' => '_et_pb_use_builder'],
                ]
            ),
        ];
    }
}
