"""تست پردازش رویدادهای Outbox."""
from __future__ import annotations

from sqlalchemy import select

from app.models.events import OutboxEvent
from app.services.tenant_service import TenantService
from app.schemas.tenant import TenantCreate
from app.workers.tasks import process_pending_outbox
from shared.events import EventStatus


async def test_outbox_event_recorded_on_tenant_create(session):
    await TenantService(session).create(
        TenantCreate(name="Evt Co", slug="evtco")
    )
    result = await session.execute(select(OutboxEvent))
    events = result.scalars().all()
    assert len(events) == 1
    assert events[0].event_type == "tenant.created"
    assert events[0].status == EventStatus.PENDING


async def test_process_pending_outbox(session):
    await TenantService(session).create(
        TenantCreate(name="Proc Co", slug="procco")
    )
    summary = await process_pending_outbox(session)
    assert summary["processed"] == 1
    assert summary["failed"] == 0

    result = await session.execute(select(OutboxEvent))
    events = result.scalars().all()
    assert all(e.status == EventStatus.PROCESSED for e in events)
    assert all(e.processed_at is not None for e in events)
