import uuid
from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import Boolean, DateTime, ForeignKey, 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.user import User


class AbsenceComment(Base):
    """Kommentar-Thread an einem Abwesenheitsantrag.

    `company_id` wird redundant gespeichert, damit die Tabelle über die normale
    company_id-RLS-Policy gefenced werden kann (kein Join nötig). System-Kommentare
    (`is_system=True`) werden bei Statuswechseln automatisch erzeugt.
    """
    __tablename__ = "absence_comments"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    absence_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("absences.id", ondelete="CASCADE"), nullable=False, index=True
    )
    company_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("companies.id", ondelete="CASCADE"), nullable=False, index=True
    )
    author_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL")
    )
    body: Mapped[str] = mapped_column(Text, nullable=False)
    is_system: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    author: Mapped["User | None"] = relationship(
        "User", primaryjoin="AbsenceComment.author_id == User.id",
        foreign_keys="[AbsenceComment.author_id]", lazy="noload",
    )

    def __repr__(self) -> str:
        return f"<AbsenceComment {self.absence_id} by {self.author_id}>"
