<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

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

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

    public function index(Request $request): JsonResponse
    {
        $filter = $this->resolveFilter($request);

        if ($this->activityService->requiresAuthentication($filter) && ! $request->user()) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

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

        return response()->json($feed);
    }

    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');
    }
}
