<?php
declare(strict_types=1);

namespace ROITheme\Shared\Infrastructure\Services;

use ROITheme\Shared\Domain\Contracts\PageContextProviderInterface;
use ROITheme\Shared\Domain\Contracts\ServerRequestProviderInterface;

/**
 * Implementacion WordPress del proveedor de contexto de pagina
 *
 * Obtiene informacion del post/pagina actual usando funciones de WordPress.
 *
 * v1.1: Renombrado de WordPressExclusionEvaluator
 *       Inyecta ServerRequestProviderInterface (no accede a $_SERVER directamente)
 *
 * @package ROITheme\Shared\Infrastructure\Services
 */
final class WordPressPageContextProvider implements PageContextProviderInterface
{
    public function __construct(
        private readonly ServerRequestProviderInterface $requestProvider
    ) {}

    public function getCurrentContext(): array
    {
        $postId = $this->getCurrentPostId();

        return [
            'post_id' => $postId,
            'categories' => $this->getPostCategories($postId),
            'url' => $this->getCurrentUrl(),
            'request_uri' => $this->requestProvider->getRequestUri(),
            'post_type' => $this->getCurrentPostType($postId),
        ];
    }

    private function getCurrentPostId(): int
    {
        if (is_singular()) {
            return get_the_ID() ?: 0;
        }

        return 0;
    }

    /**
     * @return array<array{term_id: int, slug: string, name: string}>
     */
    private function getPostCategories(int $postId): array
    {
        if ($postId === 0) {
            return [];
        }

        $categories = get_the_category($postId);

        if (empty($categories)) {
            return [];
        }

        return array_map(function (\WP_Term $term): array {
            return [
                'term_id' => $term->term_id,
                'slug' => $term->slug,
                'name' => $term->name,
            ];
        }, $categories);
    }

    private function getCurrentUrl(): string
    {
        global $wp;

        if (isset($wp->request)) {
            return home_url($wp->request);
        }

        return home_url(add_query_arg([], false));
    }

    private function getCurrentPostType(int $postId): string
    {
        if ($postId === 0) {
            return '';
        }

        return get_post_type($postId) ?: '';
    }
}
