import uuid
from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, func
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


class LdapConfig(Base):
    __tablename__ = "ldap_configs"

    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, unique=True, index=True
    )
    enabled: Mapped[bool] = mapped_column(Boolean, default=False)

    # Server
    host: Mapped[str] = mapped_column(String(255), nullable=False)
    port: Mapped[int] = mapped_column(Integer, default=389)
    use_ssl: Mapped[bool] = mapped_column(Boolean, default=False)
    use_tls: Mapped[bool] = mapped_column(Boolean, default=False)
    tls_verify: Mapped[bool] = mapped_column(Boolean, default=True)

    # Bind credentials
    bind_dn: Mapped[str] = mapped_column(Text, nullable=False)
    bind_password_encrypted: Mapped[str] = mapped_column(Text, nullable=False)

    # Search
    base_dn: Mapped[str] = mapped_column(Text, nullable=False)
    user_search_filter: Mapped[str] = mapped_column(
        String(512), nullable=False, default="(objectClass=person)"
    )

    # Attribute mapping
    attr_email: Mapped[str] = mapped_column(String(100), default="mail")
    attr_firstname: Mapped[str] = mapped_column(String(100), default="givenName")
    attr_lastname: Mapped[str] = mapped_column(String(100), default="sn")
    attr_username: Mapped[str] = mapped_column(String(100), default="sAMAccountName")
    attr_department: Mapped[str | None] = mapped_column(String(100))
    attr_personnel_number: Mapped[str | None] = mapped_column(String(100))

    # Sync state
    last_sync_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    company: Mapped["Company"] = relationship("Company", lazy="noload")

    def __repr__(self) -> str:
        return f"<LdapConfig {self.host} company={self.company_id}>"
