<?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\Actions\Remove\Handler;

use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\Person\PersonCenterHistoryRepository;

class PersonMoveCenterHistoryHandler implements PersonMoveSqlHandlerInterface
{
    public function __construct(
        private readonly PersonCenterHistoryRepository $centerHistoryRepository,
    ) {}

    public function supports(string $className, string $field): bool
    {
        return Person\PersonCenterHistory::class === $className;
    }

    public function getSqls(string $className, string $field, Person $from, Person $to): array
    {
        $sqlStatements = [];
        $oldestDateA = null;
        $oldestDateB = null;

        $oldestCenterHistoryB = null;
        $oldestCenterHistoryA = null;

        $centerHistoriesA = $this->centerHistoryRepository->findBy(['person' => $from]);
        foreach ($centerHistoriesA as $ch) {
            if (null === $oldestDateA || ($ch->getStartDate() < $oldestDateA)) {
                $oldestDateA = $ch->getStartDate();
                $oldestCenterHistoryA = $ch;
            }
        }

        $centerHistoriesB = $this->centerHistoryRepository->findBy(['person' => $to]);
        foreach ($centerHistoriesB as $ch) {
            if (null === $oldestDateB || ($ch->getStartDate() < $oldestDateB)) {
                $oldestDateB = $ch->getStartDate();
                $oldestCenterHistoryB = $ch;
            }
        }

        $sqlDelete = sprintf(<<<'SQL'
                DELETE FROM chill_person_person_center_history WHERE person_id = %d;
                SQL, $from->getId());

        $sqlStatements = [$sqlDelete];

        if ((null !== $oldestDateA && null !== $oldestDateB) && $oldestDateA <= $oldestDateB) {
            $sqlInsert = sprintf(<<<'SQL'
                UPDATE chill_person_person_center_history SET startDate = '%s' WHERE id = %d;
                SQL, $oldestDateA->format('Y-m-d'), $oldestCenterHistoryB->getId());

            $sqlStatements = [$sqlInsert, $sqlDelete];
        }

        return $sqlStatements;
    }
}
