<?php
declare(strict_types=1);

namespace ROITheme\Shared\Infrastructure\Services;

use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressComponentRepository;
use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressDefaultsRepository;

/**
 * CleanupService - Limpieza de componentes obsoletos
 *
 * RESPONSABILIDAD: Eliminar componentes que ya no existen en schema
 *
 * @package ROITheme\Infrastructure\Services
 */
final class CleanupService
{
    public function __construct(
        private WordPressComponentRepository $componentRepository,
        private WordPressDefaultsRepository $defaultsRepository
    ) {}

    /**
     * Eliminar componentes que no tienen schema
     *
     * @return array ['removed' => array]
     */
    public function removeObsolete(): array
    {
        // Obtener todos los componentes actuales
        $components = $this->componentRepository->findAll();

        // Obtener schemas disponibles
        $schemas = $this->defaultsRepository->findAll();
        $validNames = array_keys($schemas);

        $removed = [];

        foreach ($components as $component) {
            $name = $component->name()->value();

            // Si el componente no tiene schema, es obsoleto
            if (!in_array($name, $validNames)) {
                $this->componentRepository->delete($name);
                $removed[] = $name;
            }
        }

        return ['removed' => $removed];
    }
}
