"""主案与共享附件挂载关系模型。"""

from __future__ import annotations

from sqlalchemy import BigInteger, Computed, ForeignKey, Index, Integer, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column

from dms.database.base import BusinessTableMixin
from dms.extensions import db


class AttachmentBinding(BusinessTableMixin, db.Model):
    __tablename__ = "doc_attachment_binding"
    __table_args__ = (
        UniqueConstraint(
            "main_document_id",
            "attachment_document_id",
            "active_marker",
            name="uq_doc_attachment_binding_active",
        ),
        Index(
            "ix_doc_attachment_binding_main_active_sort",
            "main_document_id",
            "is_deleted",
            "sort_no",
        ),
        Index(
            "ix_doc_attachment_binding_attachment_active",
            "attachment_document_id",
            "is_deleted",
        ),
    )

    main_document_id: Mapped[int] = mapped_column(
        BigInteger,
        ForeignKey("doc_document.id", ondelete="RESTRICT"),
        nullable=False,
    )
    attachment_document_id: Mapped[int] = mapped_column(
        BigInteger,
        ForeignKey("doc_document.id", ondelete="RESTRICT"),
        nullable=False,
    )
    sort_no: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        server_default=text("0"),
    )
    active_marker: Mapped[int | None] = mapped_column(
        Integer,
        Computed("IF(is_deleted = 0, 1, NULL)", persisted=False),
        nullable=True,
    )
