"""settings and notifications

Настройки инстанса и журнал почтовых рассылок:
- `instance_settings` — key-value настройки инстанса (JSONB), бутстрап из
  `config/plugins.yaml` в lifespan backend (`services/instance_settings.py`);
- `email_deliveries` — идемпотентность рассылки саммари (уникальный частичный
  индекс по `(session_id, recipient_email)` при `kind='summary'`) и журнал
  приглашений (`kind='invitation'`, без unique — переслать обновление
  расписания обязано дублировать письмо);
- `conferences.summary_recipients` — переопределение рассылки для конкретной
  конференции (`NULL` = дефолт инстанса), `conferences.ics_sequence` —
  счётчик изменений расписания для VEVENT `SEQUENCE`;
- `users.is_blocked` — блокировка администратором, проверяется немедленно в
  `api/deps.py::_user_from_token`.

Revision ID: 5970bf64fc43
Revises: 88aa676ac140
Create Date: 2026-07-17 23:24:46.699304

"""
from typing import Sequence, Union

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


# revision identifiers, used by Alembic.
revision: str = '5970bf64fc43'
down_revision: Union[str, Sequence[str], None] = '88aa676ac140'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    op.create_table(
        'instance_settings',
        sa.Column('key', sa.String(), nullable=False),
        sa.Column('value', postgresql.JSONB(), nullable=False),
        sa.Column(
            'updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'),
            nullable=False,
        ),
        sa.PrimaryKeyConstraint('key'),
    )

    op.create_table(
        'email_deliveries',
        sa.Column('id', sa.UUID(), server_default=sa.text('gen_random_uuid()'), nullable=False),
        sa.Column('session_id', sa.UUID(), nullable=True),
        sa.Column('conference_id', sa.UUID(), nullable=True),
        sa.Column('recipient_email', sa.String(length=320), nullable=False),
        sa.Column('kind', sa.String(length=16), nullable=False),
        sa.Column(
            'sent_at', sa.DateTime(timezone=True), server_default=sa.text('now()'),
            nullable=False,
        ),
        sa.CheckConstraint("kind IN ('summary', 'invitation')", name='ck_email_deliveries_kind'),
        sa.CheckConstraint(
            '(kind = \'summary\') = (session_id IS NOT NULL)',
            name='ck_email_deliveries_summary_has_session',
        ),
        sa.CheckConstraint(
            '(kind = \'invitation\') = (conference_id IS NOT NULL)',
            name='ck_email_deliveries_invitation_has_conference',
        ),
        sa.ForeignKeyConstraint(['session_id'], ['conference_sessions.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['conference_id'], ['conferences.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id'),
    )
    op.create_index(
        'uq_email_deliveries_summary', 'email_deliveries', ['session_id', 'recipient_email'],
        unique=True, postgresql_where=sa.text("kind = 'summary'"),
    )
    op.create_index(
        'ix_email_deliveries_conference', 'email_deliveries', ['conference_id'],
    )

    op.add_column('conferences', sa.Column('summary_recipients', sa.String(length=16), nullable=True))
    op.add_column(
        'conferences',
        sa.Column('ics_sequence', sa.Integer(), server_default='0', nullable=False),
    )
    op.create_check_constraint(
        'ck_conferences_summary_recipients',
        'conferences',
        "summary_recipients IN ('all', 'owner')",
    )

    op.add_column(
        'users', sa.Column('is_blocked', sa.Boolean(), server_default='false', nullable=False)
    )


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_column('users', 'is_blocked')

    op.drop_constraint('ck_conferences_summary_recipients', 'conferences', type_='check')
    op.drop_column('conferences', 'ics_sequence')
    op.drop_column('conferences', 'summary_recipients')

    op.drop_index('ix_email_deliveries_conference', table_name='email_deliveries')
    op.drop_index('uq_email_deliveries_summary', table_name='email_deliveries')
    op.drop_table('email_deliveries')

    op.drop_table('instance_settings')
