"""
Tests CLI pour enqueue/schedule avec gestion Redis.
"""

from types import SimpleNamespace

from typer.testing import CliRunner

from pricewatch.app.cli import main as cli_main


class DummyScheduler:
    def __init__(self, *args, **kwargs) -> None:
        self.enqueue_calls = []
        self.schedule_calls = []

    def enqueue_immediate(self, url, use_playwright=None, save_db=True):
        self.enqueue_calls.append((url, use_playwright, save_db))
        return SimpleNamespace(id="job-123")

    def schedule_product(self, url, interval_hours=24, use_playwright=None, save_db=True):
        self.schedule_calls.append((url, interval_hours, use_playwright, save_db))
        return SimpleNamespace(job_id="job-456", next_run=SimpleNamespace(isoformat=lambda: "2026"))


def test_enqueue_cli_success(monkeypatch):
    """La commande enqueue retourne un job id."""
    runner = CliRunner()
    dummy = DummyScheduler()

    monkeypatch.setattr(cli_main, "ScrapingScheduler", lambda *args, **kwargs: dummy)

    result = runner.invoke(cli_main.app, ["enqueue", "https://example.com/product"])

    assert result.exit_code == 0
    assert "job-123" in result.output


def test_schedule_cli_success(monkeypatch):
    """La commande schedule retourne un job id et une date."""
    runner = CliRunner()
    dummy = DummyScheduler()

    monkeypatch.setattr(cli_main, "ScrapingScheduler", lambda *args, **kwargs: dummy)

    result = runner.invoke(
        cli_main.app,
        ["schedule", "https://example.com/product", "--interval", "12"],
    )

    assert result.exit_code == 0
    assert "job-456" in result.output
    assert "2026" in result.output


def test_enqueue_cli_redis_unavailable(monkeypatch):
    """La commande enqueue echoue si Redis est indisponible."""
    runner = CliRunner()

    def raise_redis(*args, **kwargs):
        raise cli_main.RedisUnavailableError("Redis non disponible")

    monkeypatch.setattr(cli_main, "ScrapingScheduler", raise_redis)

    result = runner.invoke(cli_main.app, ["enqueue", "https://example.com/product"])

    assert result.exit_code == 1
    assert "Redis non disponible" in result.output


def test_schedule_cli_redis_unavailable(monkeypatch):
    """La commande schedule echoue si Redis est indisponible."""
    runner = CliRunner()

    def raise_redis(*args, **kwargs):
        raise cli_main.RedisUnavailableError("Redis non disponible")

    monkeypatch.setattr(cli_main, "ScrapingScheduler", raise_redis)

    result = runner.invoke(cli_main.app, ["schedule", "https://example.com/product"])

    assert result.exit_code == 1
    assert "Redis non disponible" in result.output
