<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\Settings;
use App\Core\View;
use App\Models\Gallery;
use App\Models\GalleryImage;
use App\Models\Page;

final class GalleryController
{
    /** @param array<string,string> $params */
    public function show(Request $request, array $params): Response
    {
        $slug    = $params['slug'] ?? '';
        $gallery = Gallery::findPublishedBySlug($slug);
        $images  = $gallery !== null ? GalleryImage::publishedForGallery((int) $gallery['id']) : [];

        // Galerie accessible uniquement si publiée ET contenant au moins une image publiée.
        if ($gallery !== null && $images !== []) {
            $seoTitle = $gallery['seo_title'] ?? '';
            if (!is_string($seoTitle) || $seoTitle === '') {
                $seoTitle = (string) $gallery['title'];
            }

            return Response::html(View::render('public/gallery', [
                'pageTitle'       => $seoTitle,
                'metaDescription' => (string) ($gallery['seo_description'] ?? ''),
                'metaRobots'      => !empty($gallery['seo_noindex']) ? 'noindex, nofollow' : '',
                'gallery'         => $gallery,
                'images'          => $images,
                'batchSize'       => max(1, (int) Settings::get('gallery_batch_size', 12)),
                'lazyEnabled'     => (string) Settings::get('gallery_lazyload_enabled', '1') === '1',
            ]));
        }

        // Sinon : page éditoriale publiée, redirection, ou 404.
        $page = Page::findPublishedBySlug($slug);
        if ($page !== null) {
            $seoTitle = is_string($page['seo_title'] ?? null) && $page['seo_title'] !== ''
                ? $page['seo_title'] : (string) $page['title'];
            return Response::html(View::render('public/page', [
                'pageTitle'       => $seoTitle,
                'metaDescription' => (string) ($page['seo_description'] ?? ''),
                'metaRobots'      => !empty($page['seo_noindex']) ? 'noindex, nofollow' : '',
                'page'            => $page,
            ]));
        }

        return (new ErrorController())->notFound($request, []);
    }
}
