"""
机构网点相关的Pydantic Schema
"""
from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel, Field


# ===== 机构网点Schema =====

class OrganizationBase(BaseModel):
    """机构基础Schema"""
    org_code: str = Field(..., min_length=1, max_length=50, description="机构代码")
    org_name: str = Field(..., min_length=1, max_length=200, description="机构名称")
    org_type: str = Field(..., pattern="^(province|city|outlet)$", description="机构类型")
    parent_id: Optional[int] = Field(None, description="父机构ID")
    address: Optional[str] = Field(None, max_length=500, description="地址")
    contact_person: Optional[str] = Field(None, max_length=100, description="联系人")
    contact_phone: Optional[str] = Field(None, max_length=20, description="联系电话")
    sort_order: int = Field(default=0, description="排序")


class OrganizationCreate(OrganizationBase):
    """创建机构Schema"""
    pass


class OrganizationUpdate(BaseModel):
    """更新机构Schema"""
    org_name: Optional[str] = Field(None, min_length=1, max_length=200)
    org_type: Optional[str] = Field(None, pattern="^(province|city|outlet)$")
    parent_id: Optional[int] = None
    address: Optional[str] = Field(None, max_length=500)
    contact_person: Optional[str] = Field(None, max_length=100)
    contact_phone: Optional[str] = Field(None, max_length=20)
    status: Optional[str] = Field(None, pattern="^(active|inactive)$")
    sort_order: Optional[int] = None


class OrganizationInDB(BaseModel):
    """数据库中的机构Schema"""
    id: int
    org_code: str
    org_name: str
    org_type: str
    parent_id: Optional[int]
    tree_path: Optional[str]
    tree_level: int
    address: Optional[str]
    contact_person: Optional[str]
    contact_phone: Optional[str]
    status: str
    sort_order: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class OrganizationResponse(OrganizationInDB):
    """机构响应Schema"""
    pass


class OrganizationTreeNode(OrganizationResponse):
    """机构树节点Schema"""
    children: List["OrganizationTreeNode"] = []

    class Config:
        from_attributes = True


class OrganizationWithParent(OrganizationResponse):
    """带父机构信息的Schema"""
    parent: Optional[OrganizationResponse] = None


# 更新前向引用
OrganizationTreeNode.model_rebuild()
