"""Helpers SQL reutilisables pour eviter la duplication de JOINs."""
from sqlalchemy import text

SERVER_BASE_JOINS = """
    LEFT JOIN domain_environments de ON s.domain_env_id = de.id
    LEFT JOIN domains d ON de.domain_id = d.id
    LEFT JOIN environments e ON de.environment_id = e.id
    LEFT JOIN zones z ON s.zone_id = z.id
"""

SERVER_BASE_COLS = """
    s.id, s.hostname, s.fqdn, s.os_family, s.os_version,
    s.etat, s.tier, s.environnement, s.machine_type,
    d.name as domaine, d.code as domain_code,
    e.name as env_name, e.code as env_code,
    z.name as zone
"""

def server_list_query(where="1=1", order="s.hostname", limit=None, offset=None):
    """Construit une requete SELECT serveurs avec JOINs standard."""
    q = f"""
        SELECT {SERVER_BASE_COLS}
        FROM servers s
        {SERVER_BASE_JOINS}
        WHERE {where}
        ORDER BY {order}
    """
    if limit is not None:
        q += f" LIMIT {int(limit)}"
    if offset is not None:
        q += f" OFFSET {int(offset)}"
    return text(q)
