"""error codes

Revision ID: 82e0f9c7a952
Revises: 89d74331994c
Create Date: 2022-12-29 22:19:12.200462

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision = "82e0f9c7a952"
down_revision = "89d74331994c"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "error_codes",
        sa.Column("code", sa.Integer(), nullable=False),
        sa.Column("description", sa.String(), nullable=False),
        sa.PrimaryKeyConstraint("code"),
    )
    op.drop_column("rejected_messages", "reason")
    op.add_column(
        "rejected_messages", sa.Column("error_code", sa.Integer(), nullable=False)
    )
    op.add_column(
        "rejected_messages", sa.Column("details", postgresql.JSONB(), nullable=True)
    )

    op.execute(
        """
        INSERT INTO error_codes(code, description) VALUES 
            (-1, 'Internal error'),
            (0, 'Invalid message format'),
            (1, 'Invalid signature'),
            (2, 'Permission denied'),
            (3, 'Message content unavailable'),
            (4, 'File unavailable'),
            (100, 'Amend post ref field is empty'),
            (101, 'Cannot find original ref of amend post'),
            (102, 'Amend post cannot amend another amend'),
            (500, 'No FORGET target specified'),
            (501, 'FORGET target not found'),
            (502, 'Cannot forget a FORGET message')
        """
    )

    op.execute(
        """
        CREATE VIEW rejected_messages_view AS 
        SELECT rejected_messages.*, description FROM rejected_messages 
        LEFT OUTER JOIN error_codes 
        ON rejected_messages.error_code = error_codes.code
    """
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("DROP VIEW rejected_messages_view")
    op.drop_column("rejected_messages", "details")
    op.drop_column("rejected_messages", "error_code")
    op.add_column(
        "rejected_messages",
        sa.Column("reason", sa.VARCHAR(), autoincrement=False, nullable=False),
    )
    op.drop_table("error_codes")
    # ### end Alembic commands ###
