<?php

namespace App\Http\Controllers;

use App\Models\Translations\PostTranslation;
use Daylight\Core\Models\Page;
use Daylight\Core\Modules\Multilingualism\Entities\LocalizedRoute;
use Illuminate\View\View;

class PostController extends Controller
{
    public function __invoke(string $slug): View
    {
        $post = PostTranslation::query()
            ->whereLocale(app()->getLocale())
            ->where('slug', $slug)
            ->with([
                'post.translations',
                'post.defaultTranslation',
                'post.media',
            ])
            ->firstOrFail();

        $archive = Page::query()
            ->whereTemplate('news')
            ->with([
                'translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
            ])
            ->firstOrFail();

        $localizedRoute = LocalizedRoute::create()
            ->setRoute('news.show', $post->slug)
            ->setDefaultTranslation($post->post->defaultTranslation)
            ->setTranslations($post->post->translations);

        return view('news.show', [
            'article' => $post,
            'archive' => $archive,
            'localizedRoute' => $localizedRoute,
        ]);
    }
}
