import uuid
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from apps.worker.tasks.telegram import run_process_telegram_update, process_telegram_update_task
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import hash_webhook_secret
from modules.bots.models import BotWebhook
from modules.bots.schemas import BotRegisterRequest
from modules.bots.service import BotService
from modules.tenants.models import Tenant


@pytest.mark.asyncio
async def test_telegram_update_task_execution(db_session: AsyncSession):
    # 1. Create Tenant
    tenant_id = uuid.uuid4()
    tenant = Tenant(
        id=tenant_id,
        name="Celery Task Tenant",
        slug=f"celery-tenant-{uuid.uuid4().hex[:6]}",
        status="active",
        plan_id="enterprise",
    )
    db_session.add(tenant)
    await db_session.commit()

    # 2. Register mock bot
    unique_bot_name = f"celery_bot_{uuid.uuid4().hex[:6]}"
    token = f"celery_test_token_{uuid.uuid4().hex[:8]}_test"
    TelegramApiService.register_mock_bot(token, unique_bot_name, "Celery Bot")

    service = BotService(db_session)
    bot = await service.register_bot(
        tenant_id=tenant_id,
        req=BotRegisterRequest(token=token, name="Celery Bot", default_locale="en"),
    )
    await db_session.commit()

    # 3. Setup known webhook secret
    known_secret = "secret_for_celery_task_verification_123"
    webhook = await service.repo.get_webhook(bot.id)
    webhook.secret_hash = hash_webhook_secret(known_secret)
    await db_session.commit()

    # 4. Invoke Task with tenant context
    update_payload = {
        "update_id": 8801,
        "message": {
            "message_id": 70,
            "from": {
                "id": 554433,
                "first_name": "CeleryUser",
                "username": "celery_user",
                "language_code": "en",
            },
            "chat": {"id": 554433},
            "text": "/start",
        },
    }

    result = await run_process_telegram_update(
        bot_id=bot.id,
        received_secret=known_secret,
        update_dict=update_payload,
        tenant_id=tenant_id,
    )

    assert result.get("ok") is True
    assert result.get("processed") is True

    # 5. Invoke again with duplicate update_id -> must be detected as duplicate
    dup_result = await run_process_telegram_update(
        bot_id=bot.id,
        received_secret=known_secret,
        update_dict=update_payload,
        tenant_id=tenant_id,
    )

    assert dup_result.get("ok") is True
    assert dup_result.get("duplicate") is True
