from datetime import datetime

from sqlalchemy import ARRAY, CheckConstraint, DateTime, ForeignKey, String, Text, text
from sqlalchemy.orm import Mapped, mapped_column

from src.db.base import Base


class FormPhase(Base):
    __tablename__ = "form_phase"
    __table_args__ = (
        CheckConstraint(text("cardinality(column_keys) > 0"), name="chk_v4_form_phase_columns"),
        CheckConstraint(text("role != 'ADMIN'"), name="chk_v4_form_phase_no_admin"),
        CheckConstraint(text("closes_at > opens_at"), name="chk_v4_form_phase_window"),
        {"schema": "v3"},
    )

    budget_form_id: Mapped[int] = mapped_column(
        ForeignKey("v3.budget_form.id", ondelete="CASCADE"), primary_key=True
    )
    sheet: Mapped[str] = mapped_column(String, primary_key=True)
    phase_code: Mapped[str] = mapped_column(String, primary_key=True)
    role: Mapped[str] = mapped_column(String, ForeignKey("v3.role.code"))
    column_keys: Mapped[list[str]] = mapped_column(ARRAY(Text))
    opens_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
    closes_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
