<?php

declare(strict_types=1);

namespace App\Application\Admin\Infrastructure;

use App\Application\Admin\Service\AdminLayoutProcessor;
use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\DateTime\Clock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Http\Method;
use App\Framework\Meta\MetaData;
use App\Framework\Router\Result\ViewResult;

final readonly class ServicesController
{
    public function __construct(
        private DefaultContainer $container,
        private Clock $clock,
        private AdminLayoutProcessor $layoutProcessor,
    ) {
    }

    #[Auth]
    #[Route(path: '/admin/infrastructure/services', method: Method::GET, name: 'admin.infrastructure.services')]
    public function show(): ViewResult
    {
        $registeredServices = $this->container->getRegisteredServices();

        // The registered services are returned as a numeric array with class names as values
        $serviceNames = array_filter($registeredServices, 'is_string');
        $serviceNames = array_unique($serviceNames); // Remove duplicates
        sort($serviceNames);

        // Prepare service data with categorization
        $serviceData = [];
        foreach ($serviceNames as $serviceName) {
            // Ensure $serviceName is a string before exploding
            if (is_string($serviceName) && strpos($serviceName, '\\') !== false) {
                $parts = explode('\\', $serviceName);
                $category = $parts[1] ?? 'Unknown';
                $subCategory = $parts[2] ?? '';

                $serviceData[] = [
                    'name' => $serviceName,
                    'category' => $category,
                    'subCategory' => $subCategory,
                ];
            } else {
                // Handle non-namespaced services
                $serviceData[] = [
                    'name' => (string)$serviceName,
                    'category' => 'Other',
                    'subCategory' => '',
                ];
            }
        }

        $data = [
            'title' => 'Registrierte Dienste',
            'services' => $serviceData,
            'servicesCount' => count($serviceData),
            'current_year' => $this->clock->now()->format('Y'),
        ];

        $finalData = $this->layoutProcessor->processLayoutFromArray($data);

        return new ViewResult(
            template: 'services',
            metaData: new MetaData('Registrierte Dienste', 'Übersicht aller registrierten Services'),
            data: $finalData
        );
    }
}
