<?php
namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\ArtworkService;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class ArtworkController extends Controller
{
    protected ArtworkService $service;

    public function __construct(ArtworkService $service)
    {
        $this->service = $service;
    }

    /**
     * Browse artworks for a category (Blade view).
     */
    public function category(Request $request, Category $category): View
    {
        $perPage = (int) $request->get('per_page', 24);

        $artworks = $this->service->getCategoryArtworks($category, $perPage);

        return view('artworks.index', [
            'artworks' => $artworks,
            'category' => $category,
        ]);
    }

    /**
     * Show single artwork page by slug (Blade view).
     */
    public function show(string $slug): View
    {
        try {
            $artwork = $this->service->getPublicArtworkBySlug($slug);
        } catch (ModelNotFoundException $e) {
            abort(404);
        }

        // Prepare simple SEO meta data for Blade; keep controller thin.
        $meta = [
            'title' => $artwork->title,
            'description' => str(config($artwork->description ?? ''))->limit(160),
            'canonical' => $artwork->canonical_url ?? null,
        ];

        return view('artworks.show', [
            'artwork' => $artwork,
            'meta' => $meta,
        ]);
    }
}
