# FILE: src/apps/plots/models/plot_group.py
"""Grave grouping (INDL-41 editor mode, AC-20).

A ``PlotGroup`` links 2+ separately-owned, single-occupant plots so a couple /
family / custom grave renders as one outlined shape on the map, while each member
plot keeps its own status and linked record independently. This does NOT change
how many records a single plot can hold (that stays exactly one, by design).
"""
from __future__ import annotations

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

from geoalchemy2 import Geography
from sqlalchemy import ForeignKey, Integer, String
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.database.base import Base, TenantModel

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


class PlotGroup(TenantModel):
    __tablename__ = "plot_groups"

    tenant_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    section_id: Mapped[Optional[UUID]] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("sections.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    group_type: Mapped[str] = mapped_column(String(20), nullable=False)  # couple|family|custom
    label: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    capacity: Mapped[int] = mapped_column(Integer, default=2, nullable=False)
    boundary: Mapped[Optional[object]] = mapped_column(
        Geography(geometry_type="POLYGON", srid=4326), nullable=True
    )

    members: Mapped[List["PlotGroupMember"]] = relationship(
        "PlotGroupMember",
        back_populates="group",
        cascade="all, delete-orphan",
    )


class PlotGroupMember(Base):
    __tablename__ = "plot_group_members"

    plot_group_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("plot_groups.id", ondelete="CASCADE"),
        primary_key=True,
    )
    plot_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("plots.id", ondelete="CASCADE"),
        primary_key=True,
    )

    group: Mapped["PlotGroup"] = relationship("PlotGroup", back_populates="members")
    plot: Mapped["Plot"] = relationship("Plot")
