"""Add durable Core Forms submission storage.

Revision ID: 198
Revises: 197
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "198"
down_revision = "197"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "form_submissions",
        sa.Column("submission_id", sa.String(length=64), nullable=False),
        sa.Column("project_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("form_key", sa.String(length=64), nullable=False),
        sa.Column("values_json", postgresql.JSONB(astext_type=sa.Text()), nullable=False),
        sa.Column("accepted_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("persisted_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.Column("status", sa.String(length=32), server_default="accepted", nullable=False),
        sa.Column("client_identity", sa.Text(), nullable=True),
        sa.ForeignKeyConstraint(["project_id"], ["projects.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("submission_id"),
    )
    op.create_index(
        "ix_form_submissions_project_form_persisted",
        "form_submissions",
        ["project_id", "form_key", "persisted_at"],
    )


def downgrade() -> None:
    op.drop_index("ix_form_submissions_project_form_persisted", table_name="form_submissions")
    op.drop_table("form_submissions")
