<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

use App\Entity\Tenant\News;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class AmpController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    #[Route('/amp/haber/{slug}', name: 'frontend_amp_news')]
    public function show(string $slug): Response
    {
        $news = $this->entityManager->getRepository(News::class)
            ->findOneBy([
                'slug' => $slug,
                'status' => 'published',
                'showInAmp' => true,
            ]);

        if (!$news) {
            throw $this->createNotFoundException('AMP haber bulunamadi.');
        }

        // Related news for AMP page
        $relatedNews = [];
        if ($news->getCategory()) {
            $relatedNews = $this->entityManager->getRepository(News::class)
                ->createQueryBuilder('n')
                ->leftJoin('n.category', 'c')
                ->addSelect('c')
                ->where('n.category = :category')
                ->andWhere('n.status = :status')
                ->andWhere('n.id != :currentId')
                ->setParameter('category', $news->getCategory())
                ->setParameter('status', 'published')
                ->setParameter('currentId', $news->getId())
                ->orderBy('n.createdAt', 'DESC')
                ->setMaxResults(4)
                ->getQuery()
                ->getResult();
        }

        return $this->render('frontend/amp/news.html.twig', [
            'news' => $news,
            'relatedNews' => $relatedNews,
        ]);
    }
}
