<?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\Entity\Relationships\Relationship;

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

    public function getSqls(string $className, string $field, Person $from, Person $to): array
    {
        /*        Insert sql statement taking into account two cases.
                One where the person is the fromperson and another where the person is the toperson in the relationship.*/
        $insertSql = sprintf(<<<'SQL'
            INSERT INTO chill_person_relationships (id, relation_id, reverse, createdat, createdby_id, fromperson_id, toperson_id)
                SELECT nextval('chill_person_relationships_id_seq'), relation_id, reverse, createdat, createdby_id,
                        CASE
                           WHEN cpr.fromperson_id = %d THEN %d
                            ELSE cpr.fromperson_id
                        END as fromperson,
                        CASE
                            WHEN cpr.toperson_id = %d THEN %d
                            ELSE cpr.toperson_id
                        END as toperson
                    FROM chill_person_relationships cpr
                    WHERE fromperson_id = %d OR toperson_id = %d
                        AND NOT EXISTS (
                        SELECT 1 FROM chill_person_relationships cpr2
                                 WHERE
                                     cpr2.fromperson_id = %d AND cpr2.toperson_id = %d
                                    OR cpr2.fromperson_id = %d AND cpr2.toperson_id = %d
                                 );
        SQL, $from->getId(), $to->getId(), $from->getId(), $to->getId(), $from->getId(), $from->getId(), $to->getId(), $from->getId(), $from->getId(), $to->getId());

        $deleteSql = [
            sprintf('DELETE FROM chill_person_relationships WHERE fromperson_id = %d', $from->getId()),
            sprintf('DELETE FROM chill_person_relationships WHERE toperson_id = %d', $from->getId()),
        ];

        return [$insertSql, ...$deleteSql];
    }
}
