"""Tag and TagAssignment models for the Tags plugin."""

from __future__ import annotations

import uuid

from sqlalchemy import ForeignKey, Index, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column

from app.core.db import Base, TenantMixin


class Tag(Base, TenantMixin):
    """Tag entity — globally managed, tenant-scoped."""

    __tablename__ = "tags"
    __table_args__ = (
        UniqueConstraint("tenant_id", "name", name="uq_tags_tenant_name"),
        Index("ix_tags_tenant", "tenant_id"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    color: Mapped[str] = mapped_column(String(7), nullable=False, default="#6B7280")


class TagAssignment(Base, TenantMixin):
    """N:M assignment between tags and entities (companies, contacts, files, folders)."""

    __tablename__ = "tag_assignments"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "tag_id",
            "entity_type",
            "entity_id",
            name="uq_tag_assignments_entity",
        ),
        Index("ix_tag_assignments_tag", "tenant_id", "tag_id"),
        Index("ix_tag_assignments_entity", "tenant_id", "entity_type", "entity_id"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    tag_id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("tags.id", ondelete="CASCADE"), nullable=False
    )
    entity_type: Mapped[str] = mapped_column(String(20), nullable=False)
    entity_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False)
