<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class CategoryRedirectController extends Controller
{
    public function __invoke(Request $request, string $group, ?string $slug = null, ?string $id = null): RedirectResponse
    {
        $groupSlug = strtolower(trim($group, '/'));
        $slugPart = strtolower(trim((string) $slug, '/'));

        $category = $this->resolveCategory($groupSlug, $slugPart, $id);

        if ($category && $category->contentType) {
            $target = $category->url;

            if ($request->getQueryString()) {
                $target .= '?' . $request->getQueryString();
            }

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

        return redirect()->route('categories.index', $request->query(), 301);
    }

    private function resolveCategory(string $groupSlug, string $slugPart, ?string $id): ?Category
    {
        if ($id !== null && ctype_digit((string) $id)) {
            $category = Category::query()
                ->with('contentType')
                ->find((int) $id);

            if ($category) {
                return $category;
            }
        }

        if ($slugPart !== '') {
            $category = Category::query()
                ->with('contentType')
                ->where('slug', $slugPart)
                ->whereHas('parent', fn ($query) => $query->where('slug', $groupSlug))
                ->first();

            if ($category) {
                return $category;
            }
        }

        return Category::query()
            ->with('contentType')
            ->where('slug', $groupSlug)
            ->whereNull('parent_id')
            ->first();
    }
}
