"""
SQLAlchemy model for branches table.

Branches track named lines of development for a contract's ontology,
similar to Git branches but implemented as database records.
"""

from __future__ import annotations

import uuid

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

from pycharter.db.models.base import Base


class BranchModel(Base):
    """SQLAlchemy model for branches table."""

    __tablename__ = "branches"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    contract_id = Column(String(255), nullable=False, index=True)
    name = Column(String(255), nullable=False)
    base_version_id = Column(
        UUID(as_uuid=True),
        ForeignKey("pycharter.contract_versions.id", ondelete="SET NULL"),
        nullable=True,
    )
    status = Column(String(50), nullable=False, default="open")

    # 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__ = (
        UniqueConstraint("contract_id", "name", name="uq_branches_contract_name"),
        {"schema": "pycharter"},
    )
