<?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\DocStoreBundle\GenericDoc;

use Doctrine\DBAL\Types\Types;

final readonly class FetchQueryToSqlBuilder
{
    private const SQL = <<<'SQL'
        SELECT
            '{{ key }}' AS key,
            {{ identifiers }} AS identifiers,
            {{ date }}::date AS doc_date
        FROM {{ from }}
        {{ where }}
    SQL;

    /**
     * @return array{sql: string, params: list<mixed>, types: list<Types::*>}
     */
    public function toSql(FetchQueryInterface $query): array
    {
        $sql = strtr(self::SQL, [
            '{{ key }}' => $query->getSelectKeyString(),
            '{{ identifiers }}' => $query->getSelectIdentifierJsonB(),
            '{{ date }}' => $query->getSelectDate(),
            '{{ from }}' => $query->getFromQuery(),
            '{{ where }}' => '' === ($w = $query->getWhereQuery()) ? '' : 'WHERE '.$w,
        ]);

        $params = [
            ...$query->getSelectIdentifierParams(),
            ...$query->getSelectDateParams(),
            ...$query->getFromQueryParams(),
            ...$query->getWhereQueryParams(),
        ];

        $types = [
            ...$query->getSelectIdentifiersTypes(),
            ...$query->getSelectDateTypes(),
            ...$query->getFromQueryTypes(),
            ...$query->getWhereQueryTypes(),
        ];

        return ['sql' => $sql, 'params' => $params, 'types' => $types];
    }
}
