# FILE: src/apps/memorials/models/memorial.py
from __future__ import annotations

import datetime as dt
from typing import TYPE_CHECKING, List, Optional
from uuid import UUID

from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB, UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.database.base import TenantModel

if TYPE_CHECKING:
    from src.apps.records.models.record import Record
    from src.apps.memorials.models.memorial_photo import MemorialPhoto
    from src.apps.memorials.models.tribute import Tribute


class Memorial(TenantModel):
    __tablename__ = "memorials"

    __table_args__ = (
        UniqueConstraint("tenant_id", "slug", name="uq_memorials_tenant_slug"),
    )

    # Override tenant_id with explicit FK
    tenant_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    record_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("records.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
        index=True,
    )

    slug: Mapped[str] = mapped_column(String(255), nullable=False)
    biography_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    video_url: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    visibility_config: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    is_published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    published_at: Mapped[Optional[dt.datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )

    # Relationships
    record: Mapped["Record"] = relationship("Record", back_populates="memorial")
    photos: Mapped[List["MemorialPhoto"]] = relationship(
        "MemorialPhoto", back_populates="memorial"
    )
    tributes: Mapped[List["Tribute"]] = relationship(
        "Tribute", back_populates="memorial"
    )
