<?php

declare(strict_types=1);

namespace App\Application\Admin\Service;

use App\Application\Admin\ValueObjects\AdminLayoutData;
use App\Application\Admin\ValueObjects\Breadcrumb;
use App\Application\Admin\ValueObjects\BreadcrumbCollection;
use App\Application\Admin\ValueObjects\NavigationItem;
use App\Application\Admin\ValueObjects\NavigationMenu;
use App\Application\Admin\ValueObjects\NavigationSection;
use App\Framework\Http\HttpRequest;

final readonly class AdminLayoutProcessor
{
    public function __construct(
        private AdminNavigationService $navigationService,
        private HttpRequest $request
    ) {
    }

    /**
     * Helper method to process layout from array data (convenience method)
     */
    public function processLayoutFromArray(array $data): array
    {
        $adminLayoutData = AdminLayoutData::fromArray([
            'title' => $data['title'] ?? 'Admin',
            'currentPath' => $this->request->getPath(),
        ]);

        $processedLayoutData = $this->processAdminLayout($adminLayoutData);

        return array_merge($processedLayoutData->toArray(), $data);
    }

    public function processAdminLayout(AdminLayoutData $layoutData): AdminLayoutData
    {
        $currentPath = $this->request->path;

        try {
            $menuData = $this->navigationService->getNavigationMenu();
            $navigationMenu = $this->buildNavigationMenu($menuData, $currentPath);
        } catch (\Exception $e) {
            error_log("AdminLayoutProcessor: Failed to get navigation menu: " . $e->getMessage());
            // Fallback to default menu structure
            $navigationMenu = $this->createFallbackMenu();
        }

        try {
            $breadcrumbsData = $this->navigationService->getBreadcrumbs($currentPath);
            $breadcrumbs = $this->buildBreadcrumbs($breadcrumbsData, $currentPath);
        } catch (\Exception $e) {
            error_log("AdminLayoutProcessor: Failed to get breadcrumbs: " . $e->getMessage());
            // Fallback breadcrumbs
            $breadcrumbs = new BreadcrumbCollection([
                new Breadcrumb('Admin', '/admin'),
            ]);
        }

        return $layoutData
            ->withNavigationMenu($navigationMenu)
            ->withBreadcrumbs($breadcrumbs);
    }

    private function buildNavigationMenu(array $menuData, string $currentPath): NavigationMenu
    {
        $sections = [];
        foreach ($menuData as $sectionName => $sectionData) {
            $items = [];
            foreach ($sectionData['items'] as $name => $url) {
                $items[] = new NavigationItem(
                    name: $name,
                    url: $url,
                    isActive: $url === $currentPath
                );
            }

            $sections[] = new NavigationSection(
                name: $sectionName,
                items: $items,
                icon: $sectionData['icon'] ?? null
            );
        }

        return new NavigationMenu($sections);
    }

    private function createFallbackMenu(): NavigationMenu
    {
        $systemSection = new NavigationSection(
            name: 'System',
            items: [
                new NavigationItem('Dashboard', '/admin'),
                new NavigationItem('Health Check', '/admin/system/health'),
            ],
            icon: 'server'
        );

        return new NavigationMenu([$systemSection]);
    }

    private function buildBreadcrumbs(array $breadcrumbsData, string $currentPath): BreadcrumbCollection
    {
        $breadcrumbs = [];
        foreach ($breadcrumbsData as $breadcrumbData) {
            $breadcrumbs[] = new Breadcrumb(
                name: $breadcrumbData['name'],
                url: $breadcrumbData['url'] ?? null,
                isActive: ($breadcrumbData['url'] ?? null) === $currentPath
            );
        }

        return new BreadcrumbCollection($breadcrumbs);
    }
}
