"""
岗位（Position）数据模型
"""

from typing import Optional
from sqlalchemy import String, Integer, Text, ForeignKey, Boolean, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship
from typing import Optional, List

from .base import BaseModel, SoftDeleteMixin, AuditMixin


class Position(BaseModel, SoftDeleteMixin, AuditMixin):
    """
    岗位表

    字段说明：
    - name: 岗位名称
    - code: 岗位编码（唯一），用于稳定引用
    - description: 岗位描述
    - parent_id: 上级岗位ID，支持树形结构
    - status: 状态（active/inactive）
    """

    __tablename__ = "positions"
    __allow_unmapped__ = True

    name: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
    code: Mapped[str] = mapped_column(String(100), nullable=False, unique=True, index=True)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    parent_id: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("positions.id", ondelete="SET NULL"))
    status: Mapped[str] = mapped_column(String(20), default="active", nullable=False)
    
    # 新增字段
    skills: Mapped[Optional[List]] = mapped_column(JSON, nullable=True, comment="核心技能")
    level: Mapped[Optional[str]] = mapped_column(String(20), nullable=True, comment="岗位等级")
    sort_order: Mapped[Optional[int]] = mapped_column(Integer, default=0, nullable=True, comment="排序")

    # 关系
    parent: Mapped[Optional["Position"]] = relationship(
        "Position", remote_side="Position.id", backref="children", lazy="selectin"
    )
    
    # 成员关系（通过关联表）
    members = relationship("PositionMember", back_populates="position", cascade="all, delete-orphan")
    
    # 课程关系（通过关联表）
    courses = relationship("PositionCourse", back_populates="position", cascade="all, delete-orphan")

    def __repr__(self) -> str:
        return f"<Position(id={self.id}, name={self.name}, code={self.code}, status={self.status})>"


