<?php

declare(strict_types=1);

namespace App\Module\Widget\WidgetType;

use App\Entity\Tenant\News;
use Doctrine\ORM\EntityManagerInterface;

class PopularNewsWidget implements WidgetTypeInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    public static function getTypeSlug(): string
    {
        return 'popular_news';
    }

    public static function getTypeName(): string
    {
        return 'Populer Haberler';
    }

    public static function getConfigSchema(): array
    {
        return [
            [
                'name' => 'limit',
                'type' => 'number',
                'default' => 5,
                'label' => 'Haber Sayisi',
            ],
            [
                'name' => 'period',
                'type' => 'select',
                'default' => 'week',
                'label' => 'Zaman Dilimi',
                'options' => ['day', 'week', 'month', 'all'],
            ],
        ];
    }

    public function getData(array $config): array
    {
        $limit = (int) ($config['limit'] ?? 5);
        $period = $config['period'] ?? 'week';

        $qb = $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->where('n.status = :status')
            ->setParameter('status', 'published')
            ->orderBy('n.viewCount', 'DESC')
            ->setMaxResults($limit);

        if ($period !== 'all') {
            $dateFrom = match ($period) {
                'day' => new \DateTimeImmutable('-1 day'),
                'week' => new \DateTimeImmutable('-1 week'),
                'month' => new \DateTimeImmutable('-1 month'),
                default => new \DateTimeImmutable('-1 week'),
            };

            $qb->andWhere('n.publishedAt >= :dateFrom')
                ->setParameter('dateFrom', $dateFrom);
        }

        return $qb->getQuery()->getResult();
    }

    public function getTemplate(): string
    {
        return 'widget/popular_news.html.twig';
    }

    public static function getAllowedZones(): array
    {
        return ['sidebar', 'homepage'];
    }
}
