from datetime import datetime from sqlalchemy import JSON, DateTime, Integer, String, Text from sqlalchemy.orm import Mapped, mapped_column from app.core.constants import ActorValue from app.core.database import Base from app.core.utils.time import utc_now from app.modules.events.constants import EventSource, EventStatus class DomainEvent(Base): __tablename__ = "domain_events" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) event_id: Mapped[str] = mapped_column(String(64), unique=True, index=True) event_type: Mapped[str] = mapped_column(String(128), index=True) source: Mapped[str] = mapped_column(String(64), default=EventSource.API, index=True) aggregate_type: Mapped[str] = mapped_column(String(128), index=True) aggregate_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True) actor: Mapped[str] = mapped_column(String(128), default=ActorValue.SYSTEM, index=True) payload: Mapped[dict | None] = mapped_column(JSON, nullable=True) status: Mapped[str] = mapped_column(String(32), default=EventStatus.PENDING, index=True) attempts: Mapped[int] = mapped_column(Integer, default=0) idempotency_key: Mapped[str | None] = mapped_column( String(255), nullable=True, unique=True, index=True, ) last_error: Mapped[str | None] = mapped_column(Text, nullable=True) next_attempt_at: Mapped[datetime | None] = mapped_column( DateTime, nullable=True, index=True, ) locked_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, index=True) locked_by: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True) max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3") created_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now, index=True) processed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, index=True)