<?php
namespace App\Http\Controllers;

use App\Http\Controllers\ArtworkController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ContentRouterController extends Controller
{
    /**
     * Universal router for content-type roots, nested category paths, and artwork slugs.
     * Delegates to existing controllers to keep business logic centralized.
     */
    public function handle(Request $request, string $contentTypeSlug, ?string $categoryPath = null, $artwork = null)
    {
        if (! empty($artwork)) {
            $normalizedCategoryPath = trim((string) $categoryPath, '/');

            return app(ArtworkController::class)->show($request, $contentTypeSlug, $normalizedCategoryPath, $artwork);
        }

        $path = $categoryPath;

        // If no path provided, render the content-type landing (root) page
        if (empty($path)) {
            // Special-case photography root to use legacy controller
            if (strtolower($contentTypeSlug) === 'photography') {
                return app(\App\Http\Controllers\Legacy\PhotographyController::class)->index($request);
            }

            return app(\App\Http\Controllers\CategoryPageController::class)->show($request, $contentTypeSlug, null);
        }

        $segments = array_values(array_filter(explode('/', $path)));
        if (empty($segments)) {
            return app(\App\Http\Controllers\CategoryPageController::class)->show($request, $contentTypeSlug, null);
        }

        // Treat the last segment as an artwork slug candidate and delegate to ArtworkController::show
        $artworkSlug = array_pop($segments);
        $categoryPath = implode('/', $segments);

        return app(ArtworkController::class)->show($request, $contentTypeSlug, $categoryPath, $artworkSlug);
    }
}
