#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：module.py
模块描述：测试模块数据库模型定义

作者：czj
创建日期：2026-07-09
最后修改：2026-07-09
"""

from datetime import datetime
from typing import Optional
from sqlalchemy import String, Text, Integer, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class Module(Base):
    """
    测试模块数据库模型

    用于管理测试用例的分类，每个模块包含一组相关的测试用例。

    Attributes:
        id (str): 模块唯一标识
        name (str): 模块名称，最大长度100字符
        description (str): 模块描述
        icon (str): 模块图标标识
        order (int): 排序序号
        created_at (datetime): 创建时间
        updated_at (datetime): 更新时间

    Example:
        >>> module = Module(
        ...     id="module_abc123",
        ...     name="登录模块",
        ...     description="用户登录相关功能测试"
        ... )
    """

    __tablename__ = "modules"

    id: Mapped[str] = mapped_column(String(64), primary_key=True, comment="模块ID")
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="模块名称")
    description: Mapped[str] = mapped_column(Text, default="", comment="模块描述")
    icon: Mapped[str] = mapped_column(String(50), default="folder", comment="模块图标")
    order: Mapped[int] = mapped_column(Integer, default=0, comment="排序序号")
    module_type: Mapped[str] = mapped_column(
        String(20),
        default="standard",
        comment="模块类型: standard(标准模块)/custom(项目定制模块)"
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        comment="创建时间"
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        onupdate=datetime.utcnow,
        comment="更新时间"
    )

    # 父模块ID（支持层级结构）
    parent_id: Mapped[Optional[str]] = mapped_column(
        String(64),
        ForeignKey("modules.id"),
        nullable=True,
        default=None,
        comment="父模块ID（支持层级结构）"
    )

    # 关联用例（一对多）
    cases: Mapped[list["TestCase"]] = relationship(
        "TestCase",
        back_populates="module",
        cascade="all, delete-orphan"
    )

    # 自引用关系：父模块
    parent: Mapped[Optional["Module"]] = relationship(
        "Module",
        back_populates="children",
        remote_side=[id],
        foreign_keys=[parent_id],
        lazy="select"
    )

    # 自引用关系：子模块
    children: Mapped[list["Module"]] = relationship(
        "Module",
        back_populates="parent",
        foreign_keys=[parent_id],
        lazy="select"
    )

    def __repr__(self) -> str:
        """字符串表示"""
        return f"<Module(id={self.id}, name={self.name})>"

    def to_dict(self) -> dict:
        """
        转换为字典

        Returns:
            dict: 模块数据字典
        """
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "icon": self.icon,
            "order": self.order,
            "module_type": self.module_type,
            "parent_id": self.parent_id,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }
