# FILE: src/apps/sections/models/section.py
from __future__ import annotations

from decimal import Decimal
from typing import TYPE_CHECKING, List, Optional
from uuid import UUID

from geoalchemy2 import Geography
from sqlalchemy import (
    Boolean,
    ForeignKey,
    Integer,
    Numeric,
    SmallInteger,
    String,
    Text,
    UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.database.base import TenantModel

if TYPE_CHECKING:
    from src.apps.plots.models.plot import Plot


class Section(TenantModel):
    __tablename__ = "sections"

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_sections_tenant_code"),
    )

    # 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,
    )

    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    is_religious: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    religious_denomination: Mapped[Optional[str]] = mapped_column(
        String(100), nullable=True
    )
    founding_year: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
    notable_features: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    # ── Cemetery map geometry (INDL-49 / shared foundation for INDL-41) ──────────
    boundary: Mapped[Optional[object]] = mapped_column(
        Geography(geometry_type="POLYGON", srid=4326), nullable=True
    )
    display_color: Mapped[Optional[str]] = mapped_column(String(7), nullable=True)
    plot_number_prefix: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
    next_plot_seq: Mapped[int] = mapped_column(
        Integer, nullable=False, default=1, server_default="1"
    )
    area_m2: Mapped[Optional[Decimal]] = mapped_column(Numeric(12, 2), nullable=True)

    # Relationships
    plots: Mapped[List["Plot"]] = relationship("Plot", back_populates="section")
