<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

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

/**
 * Stories filtered by author — /stories/author/{username}
 */
final class StoriesAuthorController extends Controller
{
    public function show(Request $request, string $username): View
    {
        // Resolve by linked user username first, then by author name slug
        $author = StoryAuthor::whereHas('user', fn ($q) => $q->where('username', $username))
            ->with('user')
            ->first();

        if (! $author) {
            // Fallback: author name matches slug-style
            $author = StoryAuthor::where('name', $username)->first();
        }

        if (! $author) {
            abort(404);
        }

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

        $authorName = $author->user?->username ?? $author->name;

        return view('web.stories.author', [
            'author'                => $author,
            'stories'               => $stories,
            'page_title'            => 'Stories by ' . $authorName . ' — Skinbase',
            'page_meta_description' => 'All stories and interviews by ' . $authorName . ' on Skinbase.',
            'page_canonical'        => url('/stories/author/' . $username),
            'page_robots'           => 'index,follow',
            'breadcrumbs'           => collect([
                (object) ['name' => 'Stories', 'url' => '/stories'],
                (object) ['name' => $authorName, 'url' => '/stories/author/' . $username],
            ]),
        ]);
    }
}
