<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Export\Filter\SocialWorkFilters;

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Form\Type\PickUserOrMeDynamicType;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ReferrerFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acpw_referrer_filter';

    public function __construct(private RollingDateConverterInterface $rollingDateConverter, private UserRepositoryInterface $userRepository) {}

    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = self::PREFIX;

        $qb
            ->leftJoin('acpw.referrersHistory', $p.'_acpwusers_history')
            ->andWhere("{$p}_acpwusers_history.startDate <= :{$p}_calc_date AND ({$p}_acpwusers_history.endDate IS NULL or {$p}_acpwusers_history.endDate > :{$p}_calc_date)")
            ->andWhere("{$p}_acpwusers_history.user IN (:{$p}_agents)");

        $qb
            ->setParameter("{$p}_agents", $this->userOrMe($data['accepted_agents'], $exportGenerationContext))
            ->setParameter("{$p}_calc_date", $this->rollingDateConverter->convert(
                $data['agent_at'] ?? new RollingDate(RollingDate::T_TODAY)
            ))
        ;
    }

    public function applyOn(): string
    {
        return Declarations::SOCIAL_WORK_ACTION_TYPE;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_agents', PickUserOrMeDynamicType::class, [
                'multiple' => true,
                'label' => 'export.filter.work.by_treating_agent.Accepted agents',
            ])
            ->add('agent_at', PickRollingDateType::class, [
                'label' => 'export.filter.work.by_treating_agent.Calc date',
                'help' => 'export.filter.work.by_treating_agent.calc_date_help',
            ])
        ;
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return [
            'accepted_agents' => $this->normalizeUserOrMe($formData['accepted_agents']),
            'agent_at' => array_key_exists('agent_at', $formData) ? $formData['agent_at']?->normalize() : (new RollingDate(RollingDate::T_TODAY))->normalize(),
        ];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [
            'accepted_agents' => $this->denormalizeUserOrMe($formData['accepted_agents'], $this->userRepository),
            'agent_at' => array_key_exists('agent_at', $formData) ? RollingDate::fromNormalized($formData['agent_at']) : new RollingDate(RollingDate::T_TODAY),
        ];
    }

    public function getFormDefaultData(): array
    {
        return [
            'accepted_agents' => [],
            'agent_at' => new RollingDate(RollingDate::T_TODAY),
        ];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $users = [];

        foreach ($this->userOrMe($data['accepted_agents'], $context) as $r) {
            $users[] = $r;
        }

        return [
            'exports.filter.work.by_treating_agent.Filtered by treating agent at date', [
                'agents' => implode(', ', $users),
                'agent_at' => $this->rollingDateConverter->convert($data['agent_at'] ?? new RollingDate(RollingDate::T_TODAY)),
            ], ];
    }

    public function getTitle(): string
    {
        return 'export.filter.work.by_treating_agent.Filter by treating agent';
    }
}
