"""
Tests pour les commandes worker RQ via CLI.
"""

from types import SimpleNamespace

import pytest
from typer.testing import CliRunner

from pricewatch.app.cli import main as cli_main


class DummyRedis:
    def ping(self) -> bool:
        return True


class DummyWorker:
    def __init__(self, queues, connection=None) -> None:
        self.queues = queues
        self.connection = connection
        self.work_calls = []

    def work(self, with_scheduler: bool = True):
        self.work_calls.append(with_scheduler)


def test_worker_cli_success(monkeypatch):
    """Le worker demarre quand Redis est disponible."""
    runner = CliRunner()
    dummy_worker = DummyWorker([])

    monkeypatch.setattr(cli_main, "Worker", lambda queues, connection=None: dummy_worker)
    monkeypatch.setattr(cli_main.redis, "from_url", lambda url: DummyRedis())

    result = runner.invoke(cli_main.app, ["worker", "--no-scheduler"])

    assert result.exit_code == 0
    assert dummy_worker.work_calls == [False]


def test_worker_cli_redis_down(monkeypatch):
    """Le worker echoue proprement si Redis est indisponible."""
    runner = CliRunner()

    def raise_connection(url):
        raise cli_main.redis.exceptions.ConnectionError("redis down")

    monkeypatch.setattr(cli_main.redis, "from_url", raise_connection)

    result = runner.invoke(cli_main.app, ["worker"])

    assert result.exit_code == 1
    assert "Impossible de se connecter a Redis" in result.output
