"""Integration tests for ECMDbSync against a live server at localhost:4000."""

import unittest

from ecmind_blue_client.ecm import ECM
from ecmind_blue_client.pool import SyncPoolClient
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestECMDbSyncIntegration(unittest.TestCase):
    """Integration tests for ECMDbSync against a live server at localhost:4000."""

    @classmethod
    def setUpClass(cls):
        cls.client = SyncPoolClient(servers=ECM_SERVERS, username=ECM_USERNAME, password=ECM_PASSWORD)
        cls.ecm = ECM(cls.client)

    @classmethod
    def tearDownClass(cls):
        del cls.client

    def test_select_all_returns_result(self):
        """SELECT * FROM benutzer returns at least one row."""
        result = self.ecm.db.select("SELECT * FROM benutzer")

        self.assertGreater(len(result), 0)

    def test_select_columns_present(self):
        """Result columns include the 'benutzer' column."""
        result = self.ecm.db.select("SELECT * FROM benutzer")

        column_names = [col.name for col in result.columns]
        self.assertIn("benutzer", column_names)

    def test_select_with_string_param(self):
        """Selecting by username with %s returns the matching row."""
        result = self.ecm.db.select(
            "SELECT * FROM benutzer WHERE benutzer = %s",
            "root",
        )

        self.assertGreater(len(result), 0)
        benutzer = result.rows[0]["benutzer"]
        assert benutzer is not None
        self.assertEqual(benutzer.lower(), "root")

    def test_select_with_unquoted_table_param(self):
        """Using %u to pass the table name returns rows from that table."""
        result = self.ecm.db.select("SELECT * FROM %u", "benutzer")

        self.assertGreater(len(result), 0)

    def test_select_injection_is_escaped(self):
        """A %s injection payload returns no rows because the value is properly escaped."""
        result = self.ecm.db.select(
            "SELECT * FROM benutzer WHERE benutzer = %s",
            "' OR '1'='1",
        )

        self.assertEqual(len(result), 0)
