<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\WorldWebStory;
use App\Services\WebStories\WorldWebStorySeoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

final class WorldWebStoryController extends Controller
{
    public function __construct(private readonly WorldWebStorySeoService $seo)
    {
    }

    public function index(Request $request): View
    {
        $stories = Cache::remember('web_story_index', 300, fn () => WorldWebStory::query()
            ->with('world')
            ->visible()
            ->orderByDesc('featured')
            ->orderByDesc('published_at')
            ->paginate(12)
            ->withQueryString());

        return view('web-stories.index', [
            'stories' => $stories,
            'seo' => $this->seo->indexSeo(),
            'useUnifiedSeo' => true,
        ]);
    }

    public function show(string $slug): View
    {
        $story = Cache::remember('web_story:' . $slug, 300, fn () => WorldWebStory::query()
            ->with(['world', 'orderedPages.artwork.user'])
            ->visible()
            ->where('slug', $slug)
            ->first());

        abort_unless($story instanceof WorldWebStory, 404);

        return view('web-stories.show', [
            'story' => $story,
            'meta' => $this->seo->storyMeta($story),
        ]);
    }
}