<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Services\ArtworkService;
use App\Services\ContentTypes\ContentTypeSlugResolver;
use Illuminate\Http\Request;

class CategoryPageController extends Controller
{
    public function __construct(
        private ArtworkService $artworkService,
        private ContentTypeSlugResolver $contentTypeResolver,
    )
    {
    }

    public function show(Request $request, string $contentTypeSlug, ?string $categoryPath = null)
    {
        $resolution = $this->contentTypeResolver->resolve($contentTypeSlug);
        if (! $resolution->found() || $resolution->contentType === null) {
            abort(404);
        }

        $contentType = $resolution->contentType;

        if ($resolution->requiresRedirect()) {
            $target = url('/' . trim($contentType->slug . '/' . trim((string) $categoryPath, '/'), '/'));
            $queryString = $request->getQueryString();

            if ($queryString) {
                $target .= '?' . $queryString;
            }

            return redirect()->to($target, 301);
        }

        $sort = (string) $request->get('sort', 'latest');


        if ($categoryPath === null || $categoryPath === '') {
            // No category path: show content-type landing page (e.g., /wallpapers)
            $rootCategories = $contentType->rootCategories()->orderBy('sort_order')->orderBy('name')->get();
            $page_title = $contentType->name;
            $page_meta_description = $contentType->description ?? ($contentType->name . ' artworks on Skinbase');

            // Load artworks for this content type (show gallery on the root page)
            $perPage = 40;
            $artworks = $this->artworkService->getArtworksByContentType($contentType->slug, $perPage, $sort);

            return view('legacy::content-type', compact(
                'contentType',
                'rootCategories',
                'artworks',
                'page_title',
                'page_meta_description'
            ));
        }

        $segments = array_filter(explode('/', $categoryPath));
        $slugs = array_values(array_map('strtolower', $segments));
        if (empty($slugs)) {
            return redirect('/browse-categories');
        }

        // If the first slug exists but under a different content type, redirect to its canonical URL
        $firstSlug = $slugs[0];
        $globalRoot = Category::whereNull('parent_id')->where('slug', $firstSlug)->first();
        if ($globalRoot && $globalRoot->contentType && $globalRoot->contentType->slug !== strtolower($contentType->slug)) {
            $redirectPath = '/' . $globalRoot->contentType->slug . '/' . implode('/', $slugs);
            return redirect($redirectPath, 301);
        }

        // Resolve category by path using the helper that validates parent chain and content type
        $category = Category::findByPath($contentType->slug, $slugs);
        if (! $category) {
            abort(404);
        }
        $subcategories = $category->children()->orderBy('sort_order')->orderBy('name')->get();
        $rootCategories = $contentType->rootCategories()->orderBy('sort_order')->orderBy('name')->get();

        // Collect category ids for the category + all descendants recursively
        $collected = [];
        $gather = function (Category $cat) use (&$gather, &$collected) {
            $collected[] = $cat->id;
            foreach ($cat->children as $child) {
                $gather($child);
            }
        };
        // Ensure children relation is loaded to avoid N+1 recursion
        $category->load('children');
        $gather($category);

        // Load artworks via ArtworkService to support arbitrary-depth category paths
        $perPage = 40;
        try {
            // service expects an array with contentType slug first, then category slugs
            $pathSlugs = array_merge([strtolower($contentTypeSlug)], $slugs);
            $artworks = $this->artworkService->getArtworksByCategoryPath($pathSlugs, $perPage, $sort);
        } catch (\Throwable $e) {
            abort(404);
        }

        $page_title = $category->name;
        $page_meta_description = $category->description ?? ($contentType->name . ' artworks on Skinbase');
        $page_meta_keywords = strtolower($contentType->slug) . ', skinbase, artworks, wallpapers, skins, photography';

        // resolved category and breadcrumbs are used by the view

        return view('legacy::category-slug', compact(
            'contentType',
            'category',
            'subcategories',
            'rootCategories',
            'artworks',
            'page_title',
            'page_meta_description',
            'page_meta_keywords'
        ));
    }
}
