"""DagRun database model."""
from __future__ import annotations

from datetime import datetime

from sqlalchemy import DateTime, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from crondag.models.base import Base


class DagRunModel(Base):
    __tablename__ = "dag_run"
    __table_args__ = (
        UniqueConstraint("dag_id", "run_id", name="uq_dag_run"),
    )

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    dag_id: Mapped[str] = mapped_column(String(250), ForeignKey("dag.dag_id"), index=True)
    run_id: Mapped[str] = mapped_column(String(250), index=True)
    state: Mapped[str] = mapped_column(String(50), default="queued")
    run_type: Mapped[str] = mapped_column(String(50), default="scheduled")  # scheduled | manual
    logical_date: Mapped[datetime] = mapped_column(DateTime)
    start_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    end_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    conf: Mapped[str] = mapped_column(Text, default="{}")  # JSON
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    def __repr__(self) -> str:
        return f"<DagRunModel dag_id={self.dag_id!r} run_id={self.run_id!r} state={self.state!r}>"
