<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

use App\Entity\Tenant\Author;
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 AuthorController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    #[Route('/yazarlar', name: 'frontend_authors')]
    public function index(): Response
    {
        $authors = $this->entityManager->getRepository(Author::class)
            ->createQueryBuilder('a')
            ->where('a.isActive = :active')
            ->setParameter('active', true)
            ->orderBy('a.name', 'ASC')
            ->getQuery()
            ->getResult();

        // Get latest article for each author
        $newsRepo = $this->entityManager->getRepository(News::class);
        $authorLatestArticles = [];
        $authorArticleCounts = [];
        foreach ($authors as $author) {
            $latestArticle = $newsRepo->createQueryBuilder('n')
                ->where('n.author = :author')
                ->andWhere('n.status = :status')
                ->setParameter('author', $author)
                ->setParameter('status', 'published')
                ->orderBy('n.createdAt', 'DESC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult();
            if ($latestArticle) {
                $authorLatestArticles[$author->getId()] = $latestArticle;
            }

            $count = $newsRepo->createQueryBuilder('n')
                ->select('COUNT(n.id)')
                ->where('n.author = :author')
                ->andWhere('n.status = :status')
                ->setParameter('author', $author)
                ->setParameter('status', 'published')
                ->getQuery()
                ->getSingleScalarResult();
            $authorArticleCounts[$author->getId()] = (int) $count;
        }

        return $this->render('frontend/author/index.html.twig', [
            'authors' => $authors,
            'authorLatestArticles' => $authorLatestArticles,
            'authorArticleCounts' => $authorArticleCounts,
        ]);
    }

    #[Route('/yazar/{slug}', name: 'frontend_author_detail')]
    public function detail(string $slug): Response
    {
        $author = $this->entityManager->getRepository(Author::class)
            ->findOneBy(['slug' => $slug, 'isActive' => true]);

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

        $articles = $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->where('n.author = :author')
            ->andWhere('n.status = :status')
            ->setParameter('author', $author)
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(50)
            ->getQuery()
            ->getResult();

        return $this->render('frontend/author/detail.html.twig', [
            'author' => $author,
            'articles' => $articles,
        ]);
    }
}
