# backend/src/models/user.py
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Enum, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from config.database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="用户ID")
    username = Column(String(50), unique=True, nullable=False, index=True, comment="用户名")
    password_hash = Column(String(255), nullable=False, comment="密码哈希")
    real_name = Column(String(100), nullable=False, comment="真实姓名")
    department = Column(String(50), nullable=False, index=True, comment="部门")
    role = Column(Enum("admin", "market", "other", name="user_role"), nullable=False, index=True, comment="角色")
    email = Column(String(100), unique=True, index=True, comment="邮箱")
    phone = Column(String(20), comment="电话")
    is_active = Column(Boolean, default=True, index=True, comment="是否激活")
    created_by = Column(Integer, ForeignKey("users.id", ondelete="RESTRICT"), comment="创建人ID")
    created_at = Column(
        DateTime,
        server_default=func.now(),
        comment="创建时间",
    )
    updated_at = Column(
        DateTime,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间",
    )

    created_users = relationship("User", back_populates="creator")
    creator = relationship("User", remote_side="User.id", back_populates="created_users")
    created_projects = relationship("Project", back_populates="creator")
