<?php

declare(strict_types=1);

namespace App\Http\Controllers\RSS;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Models\Tag;
use App\Services\RSS\RSSFeedBuilder;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * TagFeedController
 *
 * GET /rss/tag/{slug} → artworks tagged with given slug (spec §3.4)
 */
final class TagFeedController extends Controller
{
    public function __construct(private readonly RSSFeedBuilder $builder) {}

    public function __invoke(string $slug): Response
    {
        $tag = Tag::where('slug', $slug)->first();

        if (! $tag) {
            throw new NotFoundHttpException("Tag [{$slug}] not found.");
        }

        $feedUrl  = url('/rss/tag/' . $slug);
        $artworks = Cache::remember('rss:tag:' . $slug, 600, fn () =>
            Artwork::public()->published()
                ->with(['user:id,username', 'categories:id,name,slug,content_type_id'])
                ->whereHas('tags', fn ($q) => $q->where('tags.id', $tag->id))
                ->latest('artworks.published_at')
                ->limit(RSSFeedBuilder::FEED_LIMIT)
                ->get()
        );

        return $this->builder->buildFromArtworks(
            ucwords(str_replace('-', ' ', $slug)) . ' Artworks',
            'Latest Skinbase artworks tagged "' . $tag->name . '".',
            $feedUrl,
            $artworks,
        );
    }
}
