<?php

namespace App\Http\Controllers;

use App\Models\RssFeed;
use App\Models\Post;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SourceController extends Controller
{
    public function show(Request $request, RssFeed $rssFeed)
    {
        // Fetch all published posts belonging to this RSS Feed source
        $posts = Post::with(['user:id,name,avatar', 'category:id,name,slug', 'rssFeed'])
            ->where('rss_feed_id', $rssFeed->id)
            ->where('status', 'published')
            ->latest()
            ->paginate(12)
            ->withQueryString();

        // Handle JSON requests for infinite scroll
        if ($request->wantsJson() && !$request->header('X-Inertia')) {
            return response()->json($posts);
        }

        // Render the Inertia page, passing the source and its initial posts
        return Inertia::render('Source/Show', [
            'source' => $rssFeed,
            'posts' => $posts,
        ]);
    }
}