"""Tests for validate.runner._rewrite_database regex substitution.

This function rewrites database-qualified SQL so that EXECUTE AS OWNER
procedures target the clone database instead of the original.
"""

from __future__ import annotations

import pytest

from test_runner.validate.runner import _rewrite_database


class TestRewriteDatabase:

    def test_simple_replacement(self):
        sql = "CALL WideWorldImporters.dbo.GetProducts()"

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == "CALL CLONE_DB.dbo.GetProducts()"

    def test_case_insensitive(self):
        sql = "call wideworldimporters.dbo.GetProducts()"

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == "call CLONE_DB.dbo.GetProducts()"

    def test_multiple_occurrences_all_replaced(self):
        sql = (
            "CALL WideWorldImporters.dbo.ProcA(); "
            "CALL WideWorldImporters.dbo.ProcB()"
        )

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == (
            "CALL CLONE_DB.dbo.ProcA(); "
            "CALL CLONE_DB.dbo.ProcB()"
        )

    def test_no_match_leaves_sql_unchanged(self):
        sql = "CALL OtherDatabase.dbo.Proc()"

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == sql

    def test_suffix_not_rewritten(self):
        """'WideWorldImporters2.dbo...' must NOT match 'WideWorldImporters'
        because re.escape produces a literal pattern that does not match
        the longer string — the trailing '2' is not part of the escaped name."""
        sql = "CALL WideWorldImporters2.dbo.Proc()"

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == sql

    @pytest.mark.parametrize("original_db", [
        "My.Database",
        "Db(test)",
    ], ids=["dot_in_name", "parens_in_name"])
    def test_special_regex_chars_in_db_name_escaped(self, original_db):
        """re.escape ensures dots and parens in the DB name are literal."""
        sql = f"CALL {original_db}.dbo.Proc()"

        result = _rewrite_database(sql, original_db, "CLONE")

        assert result == "CALL CLONE.dbo.Proc()"

    def test_standalone_name_without_dot_not_replaced(self):
        """The lookahead (?=\\.) prevents replacing bare references."""
        sql = "USE DATABASE WideWorldImporters"

        result = _rewrite_database(sql, "WideWorldImporters", "CLONE_DB")

        assert result == sql
