"""Shared read-only offer ownership queries (IDB.estatedata); the web layer must not run SQL itself (contract K4)."""
from modules.classes import DatabaseConnectionManager


def get_offer_owner(offer_id):
    """Return (exists, owner_id) for a domestic offer; owner_id is the raw ID_agenta value (may be None)."""
    with DatabaseConnectionManager() as conn:
        row = conn.execute("SELECT ID_agenta FROM estatedata WHERE ID = ?", (offer_id,)).fetchone()
    return (False, None) if row is None else (True, row[0])


def list_offer_ids_of_agent(agent_id):
    """Return the set of offer ids (as strings) whose ID_agenta equals agent_id (compared as trimmed text)."""
    with DatabaseConnectionManager() as conn:
        rows = conn.execute(
            "SELECT ID FROM estatedata WHERE TRIM(CAST(ID_agenta AS TEXT)) = ?", (str(agent_id).strip(),)
        ).fetchall()
    return {str(row[0]) for row in rows}


def list_offer_statuses_of_agent(agent_id):
    """Return the Status_oferty values (raw, NULL as None, one per offer) of the offers whose ID_agenta equals agent_id."""
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT Status_oferty FROM estatedata WHERE ID_agenta = ?", (agent_id,))
        return [row[0] for row in cursor.fetchall()]


def list_active_offers(limit):
    """Return the newest active offers (Status_oferty = "aktywna", ID descending, at most `limit`) as dicts of every column."""
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(
            'SELECT * FROM EstateData WHERE Status_oferty = "aktywna" ORDER BY ID DESC LIMIT ?', (limit,)
        )
        columns = [desc[0] for desc in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]


def list_offer_rows_by_ids(offer_ids):
    """Return raw rows (ID, title, type, status, city, region, price; NULL -> '') of the given offers joined with their localization.

    `offer_ids` must not be empty (the caller short-circuits). Ids are cast to int and bound as parameters.
    """
    placeholders = ",".join("?" for _ in offer_ids)
    with DatabaseConnectionManager() as conn:
        return conn.cursor().execute(
            f"""
            SELECT
                e.ID,
                COALESCE(e.Tytul, ''),
                COALESCE(e.Typ_nieruchomosci, ''),
                COALESCE(e.Status_oferty, ''),
                COALESCE(l.Miejscowosc, ''),
                COALESCE(l.Wojewodztwo, ''),
                COALESCE(e.Cena, '')
            FROM estatedata e
            LEFT JOIN localization l ON l.ID = e.ID
            WHERE e.ID IN ({placeholders})
            """,
            tuple(int(offer_id) for offer_id in offer_ids),
        ).fetchall()


def search_offer_rows(query="", owner_agent_id=None, limit=25):
    """Return raw rows (ID, title, type, status, price, owner, city, region) of offers matching `query`, newest ID first, at most `limit`.

    The WHERE clause is built from constant fragments; every value is a bound parameter (LIKE wildcards in `query` are not escaped).
    """
    params = []
    where = ["1 = 1"]

    if owner_agent_id is not None:
        where.append("e.ID_agenta = ?")
        params.append(int(owner_agent_id))

    normalized_query = str(query or "").strip()
    if normalized_query:
        like = f"%{normalized_query}%"
        where.append(
            """
            (
                CAST(e.ID AS TEXT) LIKE ?
                OR COALESCE(e.Tytul, '') LIKE ?
                OR COALESCE(l.Miejscowosc, '') LIKE ?
                OR COALESCE(l.Wojewodztwo, '') LIKE ?
                OR COALESCE(e.Typ_nieruchomosci, '') LIKE ?
            )
            """
        )
        params.extend([like, like, like, like, like])

    with DatabaseConnectionManager() as conn:
        return conn.cursor().execute(
            f"""
            SELECT
                e.ID,
                COALESCE(e.Tytul, ''),
                COALESCE(e.Typ_nieruchomosci, ''),
                COALESCE(e.Status_oferty, ''),
                COALESCE(e.Cena, ''),
                COALESCE(e.ID_agenta, 0),
                COALESCE(l.Miejscowosc, ''),
                COALESCE(l.Wojewodztwo, '')
            FROM estatedata e
            LEFT JOIN localization l ON l.ID = e.ID
            WHERE {' AND '.join(where)}
            ORDER BY e.ID DESC
            LIMIT ?
            """,
            [*params, int(limit)],
        ).fetchall()


def get_offer_access_row(offer_id):
    """Return the raw row (ID, owner id or 0, title, status; NULL -> '') of one offer, or None when it does not exist."""
    with DatabaseConnectionManager() as conn:
        return conn.cursor().execute(
            """
            SELECT ID, COALESCE(ID_agenta, 0), COALESCE(Tytul, ''), COALESCE(Status_oferty, '')
            FROM estatedata
            WHERE ID = ?
            LIMIT 1
            """,
            (int(offer_id),),
        ).fetchone()
