<?php
declare(strict_types=1);

namespace ROITheme\Shared\Application\UseCases\DeleteComponent;

use ROITheme\Shared\Domain\Contracts\ComponentRepositoryInterface;
use ROITheme\Shared\Domain\Contracts\CacheServiceInterface;
use ROITheme\Shared\Domain\ValueObjects\ComponentName;

/**
 * DeleteComponentUseCase - Eliminar componente
 *
 * RESPONSABILIDAD: Orquestar eliminación de componente
 *
 * FLUJO:
 * 1. Verificar que existe
 * 2. Eliminar de BD
 * 3. Invalidar cache
 * 4. Retornar confirmación
 *
 * @package ROITheme\Shared\Application\UseCases\DeleteComponent
 */
final class DeleteComponentUseCase
{
    public function __construct(
        private ComponentRepositoryInterface $repository,
        private CacheServiceInterface $cache
    ) {}

    public function execute(DeleteComponentRequest $request): DeleteComponentResponse
    {
        try {
            $componentNameString = $request->getComponentName();
            $componentName = new ComponentName($componentNameString);

            // 1. Verificar que existe
            $component = $this->repository->findByName($componentName);

            if ($component === null) {
                return DeleteComponentResponse::failure(
                    "Component '{$componentNameString}' not found"
                );
            }

            // 2. Eliminar
            $deleted = $this->repository->delete($componentName);

            if (!$deleted) {
                return DeleteComponentResponse::failure(
                    "Failed to delete component '{$componentNameString}'"
                );
            }

            // 3. Invalidar cache
            $this->cache->delete("component_{$componentNameString}");

            // 4. Retornar éxito
            return DeleteComponentResponse::success(
                "Component '{$componentNameString}' deleted successfully"
            );

        } catch (\Exception $e) {
            return DeleteComponentResponse::failure(
                'Unexpected error: ' . $e->getMessage()
            );
        }
    }
}
