"""#1714：入队成功后 celery 消息 ID 必须持久化到任务行（供清理时 revoke）。"""

from __future__ import annotations

import sys
from pathlib import Path
from unittest.mock import MagicMock

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))

from app.core import task_enqueue  # noqa: E402


class _FakeTask:
    def __init__(self):
        self.id = "task-enqueue-1"
        self.status = "pending"
        self.celery_task_id = ""

    def mark_failed(self, msg):  # noqa: ARG002
        self.status = "failed"


class _FakeRepo:
    def __init__(self):
        self.updated = None

    def count_pending_total(self):
        return 0

    def count_pending_by_user(self, user_id):  # noqa: ARG002
        return 0

    def update(self, task):
        self.updated = task
        return task


def test_safe_enqueue_persists_celery_message_id(monkeypatch):
    fake_result = MagicMock()
    fake_result.id = "celery-msg-id-enqueue-999"
    mock_celery = MagicMock()
    mock_celery.send_task.return_value = fake_result
    monkeypatch.setattr(task_enqueue, "celery_app", mock_celery)

    task = _FakeTask()
    repo = _FakeRepo()

    ok = task_enqueue.safe_enqueue_generation_task(task, repo, user_id="u1")
    assert ok is True
    # celery_task_id 已持久化
    assert task.celery_task_id == "celery-msg-id-enqueue-999"
    assert repo.updated is task
    mock_celery.send_task.assert_called_once()
    args, kwargs = mock_celery.send_task.call_args
    assert args[0] == "worker.generate_video"
    assert kwargs.get("args") == [task.id]
