import uuid
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base

if TYPE_CHECKING:
    from app.models.company import Company
    from app.models.user import User


class Department(Base):
    __tablename__ = "departments"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    company_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("companies.id", ondelete="CASCADE"), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    manager_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL", use_alter=True, name="fk_dep_manager"))

    # Relationships
    company: Mapped["Company"] = relationship("Company", back_populates="departments")
    members: Mapped[list["User"]] = relationship(
        "User",
        primaryjoin="User.department_id == Department.id",
        foreign_keys="[User.department_id]",
        back_populates="department",
        lazy="noload",
    )
    manager: Mapped["User | None"] = relationship(
        "User",
        primaryjoin="Department.manager_id == User.id",
        foreign_keys="[Department.manager_id]",
        lazy="noload",
    )

    def __repr__(self) -> str:
        return f"<Department {self.name}>"
