<?php

declare(strict_types=1);

namespace App\Http\Controllers\Post;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\Request;

class PostRelatedController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request, Post $post)
    {
        $limit = 9;

        // Get posts with matching categories
        $relatedPosts = Post::published()
            ->forApi()
            ->whereHas('categories', function ($query) use ($post): void {
                $query->whereIn('category_id', $post->categories()->pluck('category_id'));
            })
            ->where('id', '!=', $post->id)
            ->limit($limit)
            ->get();

        // If we don't have enough related posts, fill with random posts
        $remaining = $limit - $relatedPosts->count();
        if ($remaining > 0) {
            $excludeIds = $relatedPosts->pluck('id')->push($post->id);

            $randomPosts = Post::published()
                ->forApi()
                ->whereNotIn('id', $excludeIds)
                ->inRandomOrder()
                ->limit($remaining)
                ->get();

            $relatedPosts = $relatedPosts->concat($randomPosts);
        }

        return PostResource::collection($relatedPosts);
    }
}
