from __future__ import annotations

from typing import Any

from sqlalchemy.orm import Session

from services.shared.event_bus import append_outbox_event

from .sales_events import SALES_EVENT_VERSION


class SalesEventPublisher:
    producer_service = "sales-service"

    @classmethod
    def publish_sales_event(
        cls,
        session: Session,
        *,
        tenant_id: str,
        event_type: str,
        aggregate_type: str,
        aggregate_id: str,
        payload: dict[str, Any],
        actor_type: str | None = None,
        actor_id: str | None = None,
        correlation_id: str | None = None,
        causation_id: str | None = None,
    ):
        event_payload: dict[str, Any] = {
            "tenant_id": tenant_id,
            "aggregate_type": aggregate_type,
            "aggregate_id": aggregate_id,
            **payload,
        }
        if actor_type:
            event_payload["actor_type"] = actor_type
        if actor_id:
            event_payload["actor_id"] = actor_id
        if causation_id:
            event_payload["causation_id"] = causation_id

        row = append_outbox_event(
            session,
            event_type=event_type,
            producer_service=cls.producer_service,
            entity_type=aggregate_type,
            entity_id=aggregate_id,
            payload=event_payload,
            correlation_id=correlation_id,
        )
        row.event_version = SALES_EVENT_VERSION
        return row
