<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

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

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

    #[Route('/etiket/{slug}', name: 'frontend_tag')]
    public function show(string $slug, Request $request, PaginatorInterface $paginator): Response
    {
        $tag = $this->entityManager->getRepository(Tag::class)
            ->findOneBy(['slug' => $slug]);

        if (!$tag) {
            throw $this->createNotFoundException('Etiket bulunamadi.');
        }

        $qb = $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->leftJoin('n.tags', 't')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->leftJoin('n.author', 'a')
            ->addSelect('a')
            ->where('t.id = :tagId')
            ->andWhere('n.status = :status')
            ->setParameter('tagId', $tag->getId())
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC');

        $pagination = $paginator->paginate(
            $qb,
            $request->query->getInt('page', 1),
            20
        );

        return $this->render('frontend/tag/index.html.twig', [
            'tag' => $tag,
            'pagination' => $pagination,
        ]);
    }
}
