"""组织机构模型。"""

from __future__ import annotations

from sqlalchemy import BigInteger, CheckConstraint, ForeignKey, Index, String, text
from sqlalchemy.orm import Mapped, mapped_column

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


class Organization(BusinessTableMixin, db.Model):
    __tablename__ = "sys_organization"
    __table_args__ = (
        CheckConstraint(
            "status IN ('ENABLED', 'DISABLED')",
            name="organization_status",
        ),
        Index(
            "ix_sys_organization_parent_active_sort",
            "parent_id",
            "is_deleted",
            "sort_no",
        ),
        Index(
            "ix_sys_organization_status_active",
            "status",
            "is_deleted",
        ),
    )

    parent_id: Mapped[int | None] = mapped_column(
        BigInteger,
        ForeignKey("sys_organization.id", ondelete="RESTRICT"),
        nullable=True,
    )
    org_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
    org_name: Mapped[str] = mapped_column(String(128), nullable=False)
    org_path: Mapped[str] = mapped_column(String(1000), nullable=False)
    sort_no: Mapped[int] = mapped_column(nullable=False, server_default=text("0"))
    status: Mapped[str] = mapped_column(
        String(20),
        nullable=False,
        server_default=text("'ENABLED'"),
    )
