<?php

declare(strict_types=1);

namespace App\Module\Widget\WidgetType;

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

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

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

    public static function getTypeName(): string
    {
        return 'Kategori Haberleri';
    }

    public static function getConfigSchema(): array
    {
        return [
            [
                'name' => 'category_id',
                'type' => 'number',
                'default' => null,
                'label' => 'Kategori',
            ],
            [
                'name' => 'limit',
                'type' => 'number',
                'default' => 6,
                'label' => 'Haber Sayisi',
            ],
        ];
    }

    public function getData(array $config): array
    {
        $categoryId = $config['category_id'] ?? null;
        $limit = (int) ($config['limit'] ?? 6);

        if (!$categoryId) {
            return [];
        }

        return $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->where('n.category = :categoryId')
            ->andWhere('n.status = :status')
            ->setParameter('categoryId', (int) $categoryId)
            ->setParameter('status', 'published')
            ->orderBy('n.publishedAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

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

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