from __future__ import annotations

from datetime import date, datetime

from sqlalchemy import Boolean, CheckConstraint, Date, DateTime, ForeignKey, Integer, Numeric, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.db.base import Base


class Vsp(Base):
    __tablename__ = "vsp"
    __table_args__ = (
        UniqueConstraint(
            "reg_number", name="vsp_reg_number_unique",
        ),
        CheckConstraint(
            "closed_at IS NULL OR opened_at IS NULL OR closed_at >= opened_at", 
            name="chk_closed_after_opened",
        ),

        {"schema": "v3"},
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    branch_id: Mapped[int] = mapped_column(Integer, ForeignKey("v3.org_unit.id"))
    reg_number: Mapped[str | None] = mapped_column(String)
    address: Mapped[str | None] = mapped_column(String)
    format: Mapped[str | None] = mapped_column(String)
    opened_at: Mapped[date | None] = mapped_column(Date)
    placement_type: Mapped[str | None] = mapped_column(String)
    staff_count: Mapped[int | None] = mapped_column(Integer)
    total_area: Mapped[float | None] = mapped_column(Numeric)
    closed_at: Mapped[date | None] = mapped_column(Date)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    #ToDo: а нужно ли нам и is_active и is_deleted?
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
    system_code: Mapped[str | None] = mapped_column(String(100), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    created_by: Mapped[int | None] = mapped_column(Integer, ForeignKey("v3.app_user.id"))
    updated_by: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("v3.app_user.id"), nullable=True,
    )
    vsp_type: Mapped[str | None] = mapped_column(String(100), nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    rent_contract_num: Mapped[str | None] = mapped_column(String, nullable=True)
    rent_end_date : Mapped[date | None]= mapped_column(Date, nullable=True)



    org_unit = relationship("OrgUnit", back_populates="vsps")
#     budget_lines: Mapped[list["BudgetLine"]] = relationship("BudgetLine", back_populates="vsp")  # type: ignore
#     rent_details: Mapped[list["RentDetail"]] = relationship("RentDetail", back_populates="vsp")
#     security_details: Mapped[list["SecurityDetail"]] = relationship("SecurityDetail", back_populates="vsp")
#     utility_details: Mapped[list["UtilityDetail"]] = relationship("UtilityDetail", back_populates="vsp")
