<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Services\GroupService;
use App\Support\AvatarUrl;
use Closure;
use Illuminate\Http\Request;
use Inertia\Middleware;

final class HandleInertiaRequests extends Middleware
{
    protected $rootView = 'upload';

    protected function canReadSessionAuth(Request $request): bool
    {
        if ($request->attributes->get('skinbase.session_skipped') === true) {
            return false;
        }

        return $request->hasSession();
    }

    /**
     * Select the root Blade view based on route prefix.
     */
    public function rootView(Request $request): string
    {
        if ($request->path() === 'leaderboard') {
            return 'leaderboard';
        }

        if (str_starts_with($request->path(), 'admin') || str_starts_with($request->path(), 'moderation')) {
            return 'admin';
        }

        if (str_starts_with($request->path(), 'studio')) {
            return 'studio';
        }

        // Profile pages: /@{username}
        if (str_starts_with($request->path(), '@')) {
            return 'profile.show';
        }

        // Feed pages — ordered most-specific first
        if ($request->path() === 'feed/trending') {
            return 'feed.trending';
        }

        if ($request->path() === 'feed/saved') {
            return 'feed.saved';
        }

        if (str_starts_with($request->path(), 'feed')) {
            return 'feed.following';
        }

        // Hashtag pages: /tags/{tag}
        if (str_starts_with($request->path(), 'tags/')) {
            return 'feed.hashtag';
        }

        // Forum pages
        if (str_starts_with($request->path(), 'forum')) {
            return 'forum';
        }

        return $this->rootView;
    }

    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    public function handle(Request $request, Closure $next): mixed
    {
        $response = parent::handle($request, $next);

        // Prevent browsers from caching authenticated full-page SSR responses.
        // Without this, a hard reload can replay stale SSR HTML from the browser
        // cache instead of fetching fresh data from the server.
        if ($request->user() !== null) {
            $response->headers->set('Cache-Control', 'no-store, private');
        }

        return $response;
    }

    public function share(Request $request): array
    {
        $canReadSessionAuth = $this->canReadSessionAuth($request);
        $user = $canReadSessionAuth ? $request->user() : null;
        $sessionFlash = static fn (string $key): ?string => $canReadSessionAuth
            ? $request->session()->get($key)
            : null;

        return array_merge(parent::share($request), [
            'auth' => [
                'user' => $user ? [
                    'id' => $user->id,
                    'name' => $user->name,
                    'avatar_url' => $user->profile?->avatar_url ?: AvatarUrl::forUser((int) $user->id, $user->profile?->avatar_hash, 64),
                    'is_admin' => $user->isAdmin(),
                    'is_manager' => $user->isManager(),
                    'is_editorial' => $user->isEditorial(),
                    'is_staff' => $user->hasStaffAccess(),
                    'is_moderator' => $user->isModerator(),
                ] : null,
            ],
            'flash' => [
                'success' => fn (): ?string => $sessionFlash('success'),
                'error' => fn (): ?string => $sessionFlash('error'),
                'warning' => fn (): ?string => $sessionFlash('warning'),
            ],
            'cdn' => [
                'files_url' => config('cdn.files_url'),
            ],
            'features' => [
                'academy' => (bool) config('academy.enabled', true),
                'groups' => (bool) config('features.groups', true),
                'groups_v1' => (bool) config('features.groups_v1', true),
                'groups_v2' => (bool) config('features.groups_v2', true),
                'group_posts' => (bool) config('features.group_posts', true),
                'group_recruitment' => (bool) config('features.group_recruitment', true),
                'group_join_requests' => (bool) config('features.group_join_requests', true),
                'group_review_queue' => (bool) config('features.group_review_queue', true),
                'group_projects' => (bool) config('features.group_projects', true),
                'group_challenges' => (bool) config('features.group_challenges', true),
                'group_events' => (bool) config('features.group_events', true),
                'group_assets' => (bool) config('features.group_assets', true),
                'group_activity_feed' => (bool) config('features.group_activity_feed', true),
            ],
            'studio_groups' => $user
                ? app(GroupService::class)->studioOptionsForUser($user)
                : [],
        ]);
    }
}
