"""EntityLink model for the Entity Links plugin."""

from __future__ import annotations

import uuid

from sqlalchemy import 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 EntityLink(Base, TenantMixin):
    """N:M link between files/folders and companies/contacts."""

    __tablename__ = "entity_links"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "file_id",
            "entity_type",
            "entity_id",
            name="uq_entity_links_file_entity",
        ),
        Index("ix_entity_links_file", "tenant_id", "file_id"),
        Index("ix_entity_links_entity", "tenant_id", "entity_type", "entity_id"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    file_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), 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)
    created_by: Mapped[uuid.UUID | None] = mapped_column(PGUUID(as_uuid=True), nullable=True)
