"""Тест Celery-таски backfill_zone_regulations (эпик #1881).

Сеть/БД не дёргаются: мокаем SessionLocal + backfill_ekb_zone_regulations (логика backfill
покрыта tests/services/test_zone_regulation_backfill). Проверяем что таска открывает/закрывает
сессию, прокидывает limit/rate_delay_s и возвращает результат сервиса.
"""

from __future__ import annotations

from typing import Any

from app.workers.tasks import backfill_zone_regulations as task_mod


class _DB:
    def __init__(self) -> None:
        self.closed = False

    def close(self) -> None:
        self.closed = True


def test_task_wires_args_and_closes_session(monkeypatch: Any) -> None:
    db = _DB()
    captured: dict[str, Any] = {}

    def _fake_backfill(session: Any, **kwargs: Any) -> dict[str, int]:
        captured["session"] = session
        captured.update(kwargs)
        return {
            "enumerated_features": 5,
            "unique_zones": 3,
            "cached_before": 1,
            "fetched": 2,
            "upserted": 2,
            "failed": 0,
        }

    monkeypatch.setattr(task_mod, "SessionLocal", lambda: db)
    monkeypatch.setattr(task_mod, "EKBGeoportalClient", lambda *a, **kw: object())
    monkeypatch.setattr(task_mod, "backfill_ekb_zone_regulations", _fake_backfill)

    result = task_mod.backfill_zone_regulations(limit=2, rate_delay_s=0.0)

    assert result["upserted"] == 2
    assert captured["limit"] == 2
    assert captured["rate_delay_s"] == 0.0
    assert captured["session"] is db
    assert db.closed is True  # finally: db.close()
