"""Initial version

Revision ID: 5bdc013c2a92
Revises:
Create Date: 2023-10-13 10:29:57.476579

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy import (
    Column,
    TEXT,
    INTEGER,
    BLOB,
    DATETIME,
    ForeignKey,
)

# revision identifiers, used by Alembic.
revision: str = '5bdc013c2a92'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    pending_event_table = op.create_table(
        "PendingEvent",
        Column("Id", TEXT, nullable=False, primary_key=True),
        Column("CreatedAt", DATETIME, nullable=False),
        Column("ExternalCode", TEXT, nullable=True),
        Column("Subject", TEXT, nullable=False),
        Column("EventType", TEXT),
        Column("Data", BLOB),
        Column("Headers", TEXT),
        Column("AckedAt", DATETIME),
        Column("NextRetryAt", DATETIME),
        Column("RetryIndex", INTEGER),
        Column("AbandonedAt", DATETIME),
        Column("Target", TEXT),
        Column("AsyncReplySubject", TEXT),
        Column("AsyncIdField", TEXT),
        Column("AsyncId", TEXT),
    )

    op.create_index(
        index_name="PendingEvent_AsyncReplySubject_AsyncId",
        table_name="PendingEvent",
        columns=("AsyncReplySubject", "AsyncId"),
    )

    op.create_index(
        index_name="PendingEvent_ExternalCode",
        table_name="PendingEvent",
        columns=("ExternalCode",),
        unique=True,
    )

    op.create_index(
        index_name="PendingEvent_CreatedAt",
        table_name="PendingEvent",
        columns=("CreatedAt",),
    )

    op.create_table(
        "PublicationHistory",
        Column("DefinitionId", TEXT, ForeignKey(pending_event_table.c.Id), nullable=False),
        Column("CreatedAt", DATETIME, nullable=False),
        Column("Action", TEXT, nullable=False),
    )

    op.create_index(
        index_name="PublicationHistory_DefinitionId",
        table_name="PublicationHistory",
        columns=("DefinitionId", ),
    )


def downgrade() -> None:
    op.drop_table("PendingEvent")
    op.drop_table("PublicationHistory")
