from datetime import datetime

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

from src.db.base import Base


class Form3Phase(Base):
    __tablename__ = "form3_phase"
    __table_args__ = (
        CheckConstraint(text("cardinality(column_keys) > 0"), name="chk_v3_form3_phase_columns"),
        CheckConstraint(text("role != 'ADMIN'"), name="chk_v3_form3_phase_no_admin"),
        CheckConstraint(text("closes_at > opens_at"), name="chk_v3_form3_phase_window"),
        Index("ix_v3_form3_phase_active", "rf_project_report_id", "role", "opens_at", "closes_at"),
        Index("ix_v3_form3_phase_columns_gin", "column_keys", postgresql_using="gin"),
        {"schema": "v3"},
    )

    rf_project_report_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("v3.rf_project_report.id", ondelete="CASCADE"), 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))
