"""SQLAlchemy hooks — enqueue transactional changes for cloud sync."""
from __future__ import annotations

from sqlalchemy import event
from sqlalchemy.orm import Session

from app.services.cloud_sync_service import CloudSyncService, SYNC_ENTITY_MAP, should_capture_changes


def register_cloud_sync_listeners() -> None:
    @event.listens_for(Session, "before_flush")
    def _capture_sync_changes(session, flush_context, instances):
        if not should_capture_changes():
            return
        svc = CloudSyncService(session)
        for obj in list(session.new):
            if obj.__class__.__name__ in SYNC_ENTITY_MAP:
                svc.enqueue_model(obj, "upsert")
        for obj in list(session.dirty):
            if obj.__class__.__name__ in SYNC_ENTITY_MAP and session.is_modified(obj, include_collections=False):
                svc.enqueue_model(obj, "upsert")
