<?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\EntityInfo;

/**
 * Build a list of different Query parts into a single query.
 */
class AccompanyingPeriodInfoQueryBuilder
{
    private const BASE_QUERY = <<<'SQL'
            SELECT
                {period_id_column} AS accompanyingperiod_id,
                '{related_entity_column_id}' AS relatedentity,
                {related_entity_id_column_id} AS relatedentityid,
                {user_id} AS user_id,
                {datetime} AS infodate,
                '{discriminator}' AS discriminator,
                {metadata} AS metadata
            FROM {from_statement}
            {where_statement}
            SQL;

    public function buildQuery(AccompanyingPeriodInfoUnionQueryPartInterface $query): string
    {
        return strtr(
            self::BASE_QUERY,
            [
                '{period_id_column}' => $query->getAccompanyingPeriodIdColumn(),
                '{related_entity_column_id}' => $query->getRelatedEntityColumn(),
                '{related_entity_id_column_id}' => $query->getRelatedEntityIdColumn(),
                '{user_id}' => $query->getUserIdColumn(),
                '{datetime}' => $query->getDateTimeColumn(),
                '{discriminator}' => $query->getDiscriminator(),
                '{metadata}' => $query->getMetadataColumn(),
                '{from_statement}' => $query->getFromStatement(),
                '{where_statement}' => '' === $query->getWhereClause() ? '' : 'WHERE '.$query->getWhereClause(),
            ]
        );
    }
}
