from unittest.mock import MagicMock, patch

from app.jobs.channel_jobs import _execute_channel_job


def test_magento_push_images_delegates_to_sync_queue():
    session = MagicMock()
    job = MagicMock()
    job.id = 7
    job.channel_type = "magento"
    job.job_type = "push_images"
    job.native_connection_id = 1
    job.dry_run = False
    job.result = {"_options": {"limit_skus": ["A", "B"]}}

    with patch("app.jobs.channel_jobs.SqlAlchemyMagentoSyncQueueRepository") as repo_cls:
        repo = repo_cls.return_value
        repo.enqueue.return_value = 99
        result = _execute_channel_job(session, job)

    assert result["status"] == "delegated"
    assert result["queue_id"] == 99
    assert result["mode"] == "images_only"
    assert job.backend_queue_id == 99
    repo.enqueue.assert_called_once()
    call = repo.enqueue.call_args
    assert call[0][0] == 1
    assert "images" in call[0][1]
    assert call[1]["options"]["images_only"] is True
    assert call[1]["options"]["limit_skus"] == ["A", "B"]


def test_shopify_push_images_runs_media_sync():
    session = MagicMock()
    job = MagicMock()
    job.id = 12
    job.channel_type = "shopify"
    job.job_type = "push_images"
    job.channel_connection_id = 1_000_001
    job.native_connection_id = 1
    job.dry_run = True
    job.result = {"_options": {"limit": 5, "force": True}}

    with patch("shopify.media_sync.push_product_images") as push:
        push.return_value = {
            "status": "ok",
            "dry_run": True,
            "total": 3,
            "pushed": 3,
            "failed": 0,
        }
        with patch("app.jobs.channel_jobs._shopify_shop_code", return_value="demo"):
            result = _execute_channel_job(session, job)

    assert result["backend"] == "shopify_image_push"
    assert result["pushed"] == 3
    push.assert_called_once()
    kwargs = push.call_args.kwargs
    assert kwargs["dry_run"] is True
    assert kwargs["limit"] == 5
    assert kwargs["force"] is True
    assert kwargs["on_progress"] is not None
