<?php

declare(strict_types=1);

namespace App\Http\Controllers\RSS;

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

/**
 * CreatorFeedController
 *
 * GET /rss/creator/{username} → latest artworks by a given creator (spec §3.5)
 */
final class CreatorFeedController extends Controller
{
    public function __construct(private readonly RSSFeedBuilder $builder) {}

    public function __invoke(string $username): Response
    {
        $user = User::where('username', $username)->first();

        if (! $user) {
            throw new NotFoundHttpException("Creator [{$username}] not found.");
        }

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

        return $this->builder->buildFromArtworks(
            $user->username . '\'s Artworks',
            'Latest artworks by ' . $user->username . ' on Skinbase.',
            $feedUrl,
            $artworks,
        );
    }
}
