<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Story;
use App\Models\StoryTag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

/**
 * Stories filtered by tag — /stories/tag/{tag}
 */
final class StoriesTagController extends Controller
{
    public function show(Request $request, string $tag): View
    {
        $storyTag = StoryTag::where('slug', $tag)->firstOrFail();

        $stories = Cache::remember('stories:tag:' . $tag . ':page:' . ($request->get('page', 1)), 300, fn () =>
            Story::published()
                ->with('author', 'tags')
                ->whereHas('tags', fn ($q) => $q->where('stories_tags.id', $storyTag->id))
                ->orderByDesc('published_at')
                ->paginate(12)
                ->withQueryString()
        );

        return view('web.stories.tag', [
            'storyTag'              => $storyTag,
            'stories'               => $stories,
            'page_title'            => '#' . $storyTag->name . ' Stories — Skinbase',
            'page_meta_description' => 'Stories tagged with "' . $storyTag->name . '" on Skinbase.',
            'page_canonical'        => url('/stories/tag/' . $storyTag->slug),
            'page_robots'           => 'index,follow',
            'breadcrumbs'           => collect([
                (object) ['name' => 'Stories', 'url' => '/stories'],
                (object) ['name' => '#' . $storyTag->name, 'url' => '/stories/tag/' . $storyTag->slug],
            ]),
        ]);
    }
}
