<?php
declare(strict_types=1);

namespace ROITheme\Shared\Application\UseCases\EvaluatePageVisibility;

use ROITheme\Shared\Domain\Contracts\PageTypeDetectorInterface;
use ROITheme\Shared\Domain\Contracts\PageVisibilityRepositoryInterface;
use ROITheme\Shared\Domain\Constants\VisibilityDefaults;

/**
 * Caso de uso: Evaluar si un componente debe mostrarse en la página actual
 *
 * @package ROITheme\Shared\Application\UseCases\EvaluatePageVisibility
 */
final class EvaluatePageVisibilityUseCase
{
    // NOTA: Usa VisibilityDefaults::DEFAULT_VISIBILITY para cumplir DRY

    public function __construct(
        private readonly PageTypeDetectorInterface $pageTypeDetector,
        private readonly PageVisibilityRepositoryInterface $visibilityRepository
    ) {}

    /**
     * Evalúa si el componente debe mostrarse en la página actual
     */
    public function execute(string $componentName): bool
    {
        $config = $this->visibilityRepository->getVisibilityConfig($componentName);

        if (empty($config)) {
            // Usar constante compartida (DRY)
            $config = VisibilityDefaults::DEFAULT_VISIBILITY;
        }

        $pageType = $this->pageTypeDetector->detect();
        $visibilityField = $pageType->toVisibilityField();

        return $this->toBool($config[$visibilityField] ?? true);
    }

    private function toBool(mixed $value): bool
    {
        return $value === true || $value === '1' || $value === 1;
    }
}
