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

from typing import TYPE_CHECKING, Optional
from uuid import UUID

from sqlalchemy import Boolean, ForeignKey, Numeric, 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 Base, TenantModel

if TYPE_CHECKING:
    from src.apps.records.models.record import Record
    from src.apps.plots.models.plot_type import PlotType
    from src.apps.sections.models.section import Section


class Plot(TenantModel):
    __tablename__ = "plots"

    __table_args__ = (
        UniqueConstraint("tenant_id", "plot_ref", name="uq_plots_tenant_ref"),
    )

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

    plot_ref: Mapped[str] = mapped_column(String(50), nullable=False)
    section_id: Mapped[Optional[UUID]] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("sections.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    plot_type_id: Mapped[Optional[UUID]] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("plot_types.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    status: Mapped[str] = mapped_column(
        String(20), default="vacant", nullable=False, index=True
    )
    latitude: Mapped[Optional[float]] = mapped_column(Numeric(10, 7), nullable=True)
    longitude: Mapped[Optional[float]] = mapped_column(Numeric(10, 7), nullable=True)
    price_override: Mapped[Optional[float]] = mapped_column(
        Numeric(10, 2), nullable=True
    )
    notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    is_veteran_section: Mapped[bool] = mapped_column(
        Boolean, default=False, nullable=False
    )

    # Relationships
    section: Mapped[Optional["Section"]] = relationship(
        "Section", back_populates="plots"
    )
    plot_type: Mapped[Optional["PlotType"]] = relationship(
        "PlotType", back_populates="plots"
    )
    record: Mapped[Optional["Record"]] = relationship(
        "Record", uselist=False, back_populates="plot"
    )
