from __future__ import annotations

from datetime import datetime

from sqlalchemy import BigInteger, DateTime, String, func
from sqlalchemy.orm import Mapped, mapped_column

from supply_infra.db.base import Base


class PipelineLock(Base):
    """Auditable lease used for cross-process pipeline coordination."""

    __tablename__ = "pipeline_lock"

    lock_key: Mapped[str] = mapped_column(String(191), primary_key=True)
    owner_run_id: Mapped[str] = mapped_column(String(36), nullable=False)
    owner_instance: Mapped[str] = mapped_column(String(191), nullable=False)
    lease_until: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    heartbeat_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    version: Mapped[int] = mapped_column(BigInteger, nullable=False, default=1)
    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        nullable=False,
        server_default=func.now(),
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
    )
