<?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\Service\AccompanyingPeriod;

use Chill\DocStoreBundle\Entity\AccompanyingCourseDocument;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;

class OldDraftAccompanyingPeriodRemover implements OldDraftAccompanyingPeriodRemoverInterface
{
    public function __construct(private readonly EntityManagerInterface $em, private readonly LoggerInterface $logger) {}

    public function remove(\DateInterval $interval): void
    {
        $this->logger->debug('['.self::class.'] start to remove old periods', [
            'interval' => $interval->format('%d days'),
        ]);

        $beforeDate = (new \DateTimeImmutable('now'))->sub($interval);

        $results = $this->em->wrapInTransaction(static function (EntityManagerInterface $em) use ($beforeDate) {
            $subDQL = 'SELECT p FROM '.AccompanyingPeriod::class.' p WHERE p.createdAt < :beforeDate AND p.step = :draft';
            $parameters = [
                'beforeDate' => $beforeDate,
                'draft' => AccompanyingPeriod::STEP_DRAFT,
            ];

            $resources = $em->createQuery(
                'DELETE '.AccompanyingPeriod\Resource::class." r  WHERE r.accompanyingPeriod IN ({$subDQL})"
            )
                ->setParameters($parameters)
                ->getSingleScalarResult();

            $participations = $em->createQuery(
                'DELETE '.AccompanyingPeriodParticipation::class." part WHERE part.accompanyingPeriod IN ({$subDQL})"
            )
                ->setParameters($parameters)
                ->getSingleScalarResult();

            $userHistory = $em->createQuery(
                'DELETE '.AccompanyingPeriod\UserHistory::class." h WHERE h.accompanyingPeriod IN ({$subDQL})"
            )
                ->setParameters($parameters)
                ->getSingleScalarResult();

            $comments = $em->createQuery(
                'DELETE '.AccompanyingPeriod\Comment::class." c WHERE c.accompanyingPeriod IN ({$subDQL})"
            )
                ->setParameters($parameters)
                ->getSingleScalarResult();

            $documents = $em->createQuery(
                'DELETE '.AccompanyingCourseDocument::class." d WHERE d.course IN ({$subDQL})"
            )
                ->setParameters($parameters)
                ->getSingleScalarResult();

            $periods = $em
                ->createQuery(
                    'DELETE '.AccompanyingPeriod::class.' p WHERE p.createdAt < :beforeDate
                    AND p.step = :draft'
                )
                ->setParameter(':beforeDate', $beforeDate, Types::DATETIME_IMMUTABLE)
                ->setParameter(':draft', AccompanyingPeriod::STEP_DRAFT)
                ->getSingleScalarResult();

            return [
                'comments' => $comments,
                'documents' => $documents,
                'participations' => $participations,
                'periods' => $periods,
                'resources' => $resources,
                'userHistory' => $userHistory,
            ];
        });

        $this->logger->info('['.self::class.'] periods removed', array_merge($results, [
            'interval' => $interval->format('%d days'),
        ]));
    }
}
