<?php

namespace KupShop\KupShopBundle\Util\Database;

class QueryHint
{
    public const ROUTE_TO_MASTER_HINT = ' -- maxscale route to master';

    public static function routeToMaster($activate = true)
    {
        if ($activate) {
            sqlQuery('select 1 -- maxscale begin route to master');
        } else {
            sqlQuery('select 1 -- maxscale end');
        }
    }

    /**
     * @template T
     *
     * @param callable(): T $fn
     *
     * @return T
     */
    public static function withRouteToMaster(callable $fn): mixed
    {
        static::routeToMaster();

        $result = $fn();

        static::routeToMaster(false);

        return $result;
    }

    public static function hint(string $query): string
    {
        // in administration all trafic should be routed to master db
        if (isAdministration() && !str_contains($query, '-- maxscale')) {
            $query .= self::ROUTE_TO_MASTER_HINT;
        }

        return $query;
    }
}
