"""
SQLAlchemy model for contract_versions table.

Stores versioned snapshots of ontology content as JSONB,
forming an event-sourced version history linked by parent_id.
"""

from __future__ import annotations

import uuid

from sqlalchemy import Column, DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.sql import func

from pycharter.db.models.base import Base


class ContractVersionModel(Base):
    """SQLAlchemy model for contract_versions table."""

    __tablename__ = "contract_versions"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    contract_id = Column(String(255), nullable=False, index=True)
    parent_id = Column(
        UUID(as_uuid=True),
        ForeignKey("pycharter.contract_versions.id", ondelete="SET NULL"),
        nullable=True,
    )
    branch_id = Column(
        UUID(as_uuid=True),
        ForeignKey("pycharter.branches.id", ondelete="SET NULL"),
        nullable=True,
    )
    content = Column(JSONB, nullable=False)
    message = Column(Text, nullable=False)
    author = Column(String(255), nullable=False)
    status = Column(String(50), nullable=False, default="active")

    # Audit fields
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    created_by = Column(String(255), nullable=True)
    updated_by = Column(String(255), nullable=True)

    __table_args__ = ({"schema": "pycharter"},)
