<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\CommunityActivityService;
use Illuminate\Http\Request;

final class CommunityActivityController extends Controller
{
    public function __construct(private readonly CommunityActivityService $activityService)
    {
    }

    public function index(Request $request)
    {
        $filter = $this->resolveFilter($request);
        if ($this->activityService->requiresAuthentication($filter) && ! $request->user()) {
            $filter = 'all';
        }

        $feed = $this->activityService->getFeed(
            viewer: $request->user(),
            filter: $filter,
            page: 1,
            perPage: CommunityActivityService::DEFAULT_PER_PAGE,
            actorUserId: $request->filled('user_id') ? (int) $request->query('user_id') : null,
        );

        return view('web.comments.latest', [
            'page_title' => 'Community Activity',
            'props' => [
                'initialActivities' => $feed['data'],
                'initialMeta' => $feed['meta'],
                'initialFilter' => $feed['filter'],
                'initialUserId' => $request->filled('user_id') ? (int) $request->query('user_id') : null,
                'isAuthenticated' => (bool) $request->user(),
            ],
            'initialFilter' => $feed['filter'],
            'initialUserId' => $request->filled('user_id') ? (int) $request->query('user_id') : null,
        ]);
    }

    private function resolveFilter(Request $request): string
    {
        if ($request->filled('type') && ! $request->filled('filter')) {
            return (string) $request->query('type', 'all');
        }

        if ($request->boolean('following') && ! $request->filled('filter')) {
            return 'following';
        }

        return (string) $request->query('filter', 'all');
    }
}
