import uuid

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

from api.models.base import Base, TimestampMixin, new_uuid


class CapabilityCatalog(Base, TimestampMixin):
    __tablename__ = "capability_catalog"
    __table_args__ = (
        UniqueConstraint("domain_id", "capability_type", "title", name="uq_catalog_domain_type_title"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=new_uuid
    )
    domain_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("domains.id", ondelete="RESTRICT"),
        nullable=False,
        index=True,
    )
    repo_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("managed_repos.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    capability_type: Mapped[str] = mapped_column(String(50), nullable=False)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    keywords: Mapped[list[str]] = mapped_column(
        ARRAY(String), nullable=False, server_default="{}"
    )
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default="active", server_default="active"
    )

    domain: Mapped["Domain"] = relationship("Domain", lazy="selectin")  # noqa: F821
    repo: Mapped["ManagedRepo | None"] = relationship("ManagedRepo", lazy="selectin")  # noqa: F821

    @property
    def domain_slug(self) -> str:
        return self.domain.slug if self.domain is not None else ""

    @property
    def repo_slug(self) -> str | None:
        return self.repo.slug if self.repo is not None else None
