<?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\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Entity\Person;

class PersonMoveAccompanyingPeriodParticipationHandler implements PersonMoveSqlHandlerInterface
{
    public function supports(string $className, string $field): bool
    {
        return AccompanyingPeriodParticipation::class === $className;
    }

    public function getSqls(string $className, string $field, Person $from, Person $to): array
    {
        $insertSql = sprintf(<<<'SQL'
            INSERT INTO chill_person_accompanying_period_participation (person_id, accompanyingperiod_id, id, startdate, enddate)
                SELECT %d, accompanyingperiod_id, nextval('chill_person_accompanying_period_participation_id_seq'), startdate, enddate
                    FROM chill_person_accompanying_period_participation cpapp
                    WHERE person_id = %d
                        AND NOT EXISTS (
                        SELECT 1 FROM chill_person_accompanying_period_participation cpapp2
                                 WHERE
                                     person_id = %d
                                   AND (cpapp.startdate, COALESCE(cpapp.enddate, 'infinity'::date)) OVERLAPS (cpapp2.startdate, COALESCE(cpapp2.enddate, 'infinity'::date))
                                 );
        SQL, $to->getId(), $from->getId(), $to->getId());

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

        return [$insertSql, $deleteSql];
    }
}
