# FILE: src/apps/plots/models/plot_type.py
from __future__ import annotations

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

from sqlalchemy import Column, ForeignKey, Integer, Numeric, String, Table
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
    from src.apps.sections.models.section import Section


# Junction table for PlotType <-> Section (INDL-51). Plain Table (not an ORM
# model) since no extra columns/behavior are needed beyond the two FKs — see
# `PlotType.sections` relationship below, which uses this via `secondary=`.
plot_type_sections = Table(
    "plot_type_sections",
    Base.metadata,
    Column(
        "plot_type_id",
        PG_UUID(as_uuid=True),
        ForeignKey("plot_types.id", ondelete="CASCADE"),
        primary_key=True,
    ),
    Column(
        "section_id",
        PG_UUID(as_uuid=True),
        ForeignKey("sections.id", ondelete="RESTRICT"),
        primary_key=True,
    ),
)


class PlotType(TenantModel):
    __tablename__ = "plot_types"

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

    name: Mapped[str] = mapped_column(String(100), nullable=False)
    default_width_m: Mapped[Optional[float]] = mapped_column(
        Numeric(6, 2), nullable=True
    )
    default_length_m: Mapped[Optional[float]] = mapped_column(
        Numeric(6, 2), nullable=True
    )
    default_depth_m: Mapped[Optional[float]] = mapped_column(
        Numeric(6, 2), nullable=True
    )
    capacity: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    default_price: Mapped[Optional[float]] = mapped_column(
        Numeric(10, 2), nullable=True
    )

    # Relationships
    plots: Mapped[List["Plot"]] = relationship("Plot", back_populates="plot_type")
    sections: Mapped[List["Section"]] = relationship(
        "Section", secondary=plot_type_sections
    )
