import json
import os

import aio_pika

RABBITMQ_URL: str = os.getenv("RABBITMQ_URL", "amqp://user:password@rabbitmq/")
QUEUE_NAME: str = "ticket_events"


async def publish_ticket_paid_event(ticket_id: int, user_id: int) -> None:
    """Публикует событие ticket_paid в очередь RabbitMQ.

    Формат совпадает с тем, что ожидает worker.py:
    {"action": "ticket_paid", "ticket_id": <int>, "user_id": <int>}
    """
    connection = await aio_pika.connect_robust(RABBITMQ_URL)
    async with connection:
        channel = await connection.channel()

        # durable=True — очередь переживёт перезапуск брокера
        queue = await channel.declare_queue(QUEUE_NAME, durable=True)

        body = json.dumps(
            {"action": "ticket_paid", "ticket_id": ticket_id, "user_id": user_id}
        ).encode()

        await channel.default_exchange.publish(
            aio_pika.Message(
                body=body,
                delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
                content_type="application/json",
            ),
            routing_key=queue.name,
        )
