<?php

namespace MintyPHP\Support\Search;

class SearchQueryNormalizer
{
    // Prepares a user query for SQL LIKE. Escapes \ and _ (LIKE special chars),
    // converts * to %, and wraps with % wildcards if not already present.
    public static function normalizeLikeQuery(string $query): string
    {
        $query = trim($query);
        if ($query === '') {
            return '';
        }

        $query = str_replace('\\', '\\\\', $query);
        $query = str_replace('_', '\\_', $query);
        $query = str_replace('*', '%', $query);

        if (!str_starts_with($query, '%')) {
            $query = '%' . $query;
        }
        if (!str_ends_with($query, '%')) {
            $query .= '%';
        }

        return $query;
    }

    // Strips wildcard chars for relevance scoring — score queries need a clean term, not a LIKE pattern.
    public static function normalizeScoreQuery(string $query): string
    {
        $query = trim($query);
        if ($query === '') {
            return '';
        }

        return str_replace(['*', '%', '_'], '', $query);
    }
}
