"""Tagging models for meetings."""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING
from uuid import UUID as PyUUID
from uuid import uuid4

from sqlalchemy import DateTime, ForeignKey, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from noteflow.domain.utils.time import utc_now

from .._base import Base

if TYPE_CHECKING:
    from noteflow.infrastructure.persistence.models.core.meeting import MeetingModel
    from noteflow.infrastructure.persistence.models.identity.identity import (
        WorkspaceModel,
    )


class TagModel(Base):
    """Represent a tag that can be applied to meetings."""

    __tablename__ = "tags"
    __table_args__: tuple[UniqueConstraint, dict[str, str]] = (
        UniqueConstraint("workspace_id", "name", name="tags_unique_name_per_workspace"),
        {"schema": "noteflow"},
    )

    id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        default=uuid4,
    )
    workspace_id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.workspaces.id", ondelete="CASCADE"),
        nullable=False,
    )
    name: Mapped[str] = mapped_column(Text, nullable=False)
    color: Mapped[str] = mapped_column(Text, nullable=False, default="#888888")
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=utc_now,
    )

    # Relationships
    workspace: Mapped[WorkspaceModel] = relationship(
        "WorkspaceModel",
        back_populates="tags",
    )
    meeting_tags: Mapped[list[MeetingTagModel]] = relationship(
        "MeetingTagModel",
        back_populates="tag",
        cascade="all, delete-orphan",
    )


class MeetingTagModel(Base):
    """Junction table linking meetings to tags."""

    __tablename__ = "meeting_tags"
    __table_args__: dict[str, str] = {"schema": "noteflow"}

    meeting_id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.meetings.id", ondelete="CASCADE"),
        primary_key=True,
    )
    tag_id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.tags.id", ondelete="CASCADE"),
        primary_key=True,
    )

    # Relationships
    meeting: Mapped[MeetingModel] = relationship(
        "MeetingModel",
        back_populates="meeting_tags",
    )
    tag: Mapped[TagModel] = relationship(
        "TagModel",
        back_populates="meeting_tags",
    )
