"""add reminders_disabled to users

Revision ID: 9bac7bf02e38
Revises: c3aafcd58735
Create Date: 2026-04-14 03:30:00.000000

Adds a `reminders_disabled` BOOLEAN column to `users` so the opt-out preference
is persisted in Postgres instead of Redis (which was volatile and fail-opened
when unreachable).

On upgrade, attempts a one-time Redis -> DB sync so existing opt-outs are
preserved. Silently skips if Redis is unavailable.
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = '9bac7bf02e38'
down_revision: Union[str, None] = 'c3aafcd58735'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        'users',
        sa.Column(
            'reminders_disabled',
            sa.Boolean(),
            server_default=sa.text('false'),
            nullable=False,
        ),
    )

    # Best-effort: migrate existing opt-outs from Redis so users don't start
    # receiving emails they had previously turned off.
    try:
        import os
        import json
        import redis

        redis_url = os.environ.get('REDIS_URL')
        if not redis_url:
            return

        r = redis.from_url(redis_url, decode_responses=True, socket_connect_timeout=3)
        conn = op.get_bind()
        for key in r.scan_iter('user_settings:*', count=100):
            try:
                raw = r.get(key)
                if not raw:
                    continue
                data = json.loads(raw)
                if not data.get('reminders_disabled'):
                    continue
                uid = int(key.split(':', 1)[1])
                conn.execute(
                    sa.text('UPDATE users SET reminders_disabled = TRUE WHERE id = :uid'),
                    {'uid': uid},
                )
            except Exception:
                continue
    except Exception:
        pass


def downgrade() -> None:
    op.drop_column('users', 'reminders_disabled')
