<?php

namespace App\Http\Controllers;

use Daylight\Core\Models\Category;
use Daylight\Core\Modules\Multilingualism\Entities\LocalizedRoute;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function __invoke(Request $request, string $category)
    {
        $category = $this->findCategoryBySlug(
            slugs: $this->parseSlug($category),
            with: [
                'translations.components.relatables',
                'translations.components.media',
                'ancestorsAndSelf.translations' => function ($q) {
                    $q->where('locale', app()->getLocale());
                },
                'siblingsAndSelf.translations' => function ($q) {
                    $q->where('locale', app()->getLocale());
                },
            ]
        );

        if (! $category) {
            abort(404);
        }

        $localizedRoute = LocalizedRoute::create()
            ->setRoute('products.category', $category->translations->first()->nestedSlug)
            ->setDefaultTranslation($category->defaultTranslation)
            ->setTranslations($category->translations);

        return view('products.category', [
            'category' => $category,
            'localizedRoute' => $localizedRoute,
        ]);
    }

    private function parseSlug(string $slug): array
    {
        return explode('/', $slug);
    }

    private function findCategoryBySlug(array $slugs, array $with = []): Category|bool
    {
        return collect($slugs)->reduce(function ($category, $slug) use ($with) {
            $query = $category
                ? $category->descendants()
                : Category::query();

            $category = $query
                ->whereHas('translations', function ($q) use ($slug) {
                    $q->where('slug', $slug)->where('locale', app()->getLocale());
                })
                ->with(
                    array_merge([
                        'translations' => function ($q) use ($slug) {
                            $q->where('locale', app()->getLocale())->where('slug', $slug);
                        },
                        $category ? 'defaultTranslation.category.ancestorsAndSelf' : 'defaultTranslation',
                    ], $with)
                )
                ->first();

            return $category ?: false;
        });
    }
}
