"""
Shared constants and data helpers for live integration tests.

All DML goes through executemany() → POST /api/batch, which requires at least
one parameter set.  date_of_birth is inlined as a SQL literal to avoid a
VARCHAR→DATE type mismatch that causes the live API to silently reject the row.
"""

import uuid

TABLE = "[PostgreSQLPythonConnectorIntegrationTest].[public].[users]"
SP    = "[PostgreSQLPythonConnectorIntegrationTest].[public]"

# Unique hex token per test session — scopes test data, no SQL wildcard chars.
_RUN_ID = uuid.uuid4().hex[:10]


def make_email(tag: str) -> str:
    """Unique test email scoped to this run and tag."""
    return f"lt{_RUN_ID}{tag}@test.invalid"


def company(tag: str) -> str:
    """Unique company name scoped to this run and tag."""
    return f"TestCo{_RUN_ID}{tag}"


_DEFAULT_USER = dict(
    first_name="TestFirst",
    last_name="TestLast",
    phone="+1-555-0000",
    dob="1990-01-15",
    gender="Other",
    country="USA",
    city="TestCity",
    address="1 Test Street",
    occupation="Tester",
    company="TestCorp",
)


def insert_user(cur, user_email: str, **overrides) -> None:
    """Insert one test user via parameterised INSERT → /batch."""
    fields = {**_DEFAULT_USER, **overrides}
    cur.executemany(
        f"INSERT INTO {TABLE} "
        "(first_name, last_name, email, phone, date_of_birth, gender, "
        "country, city, address, occupation, company) VALUES "
        f"(@fn, @ln, @em, @ph, '{fields['dob']}', @gn, @co, @ci, @ad, @oc, @cm)",
        [{
            "@fn": fields["first_name"],
            "@ln": fields["last_name"],
            "@em": user_email,
            "@ph": fields["phone"],
            "@gn": fields["gender"],
            "@co": fields["country"],
            "@ci": fields["city"],
            "@ad": fields["address"],
            "@oc": fields["occupation"],
            "@cm": fields["company"],
        }],
    )


def get_user_id(cur, user_email: str) -> int | None:
    """Return the id of the user matching email, or None."""
    cur.execute(f"SELECT id FROM {TABLE} WHERE email = '{user_email}'")
    row = cur.fetchone()
    return int(row[0]) if row else None


def cleanup(cur, *emails: str) -> None:
    """Delete test rows by exact email in a single batch call; silently ignores errors."""
    if not emails:
        return
    try:
        cur.executemany(
            f"DELETE FROM {TABLE} WHERE email = @em",
            [{"@em": e} for e in emails],
        )
    except Exception:
        pass
