"""end-to-end encrypted messages + system messages

Revision ID: 0027_message_e2ee
Revises: 0026_messages
Create Date: 2026-06-25

Reworks direct messaging for end-to-end encryption. The `messages` table now stores ciphertext
(+ iv) for private user-to-user messages instead of plaintext `body`; `body` is kept (nullable)
for server-authored `kind="system"` messages (welcome / announcements). Adds `message_keys` to
hold each user's public key + passphrase-wrapped private key (the server can never decrypt).

Any pre-existing rows were plaintext with no keys, so they're dropped (the feature is unshipped;
prod has none).
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0027_message_e2ee"
down_revision: Union[str, None] = "0026_messages"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Old rows were plaintext with no E2EE keys — can't be migrated; drop them.
    op.execute("DELETE FROM messages")
    op.add_column(
        "messages",
        sa.Column("kind", sa.String(length=16), nullable=False, server_default="user"),
    )
    op.add_column("messages", sa.Column("ciphertext", sa.Text(), nullable=True))
    op.add_column("messages", sa.Column("iv", sa.String(length=32), nullable=True))
    # System messages have no human sender and carry plaintext `body`.
    op.alter_column("messages", "sender_id", existing_type=sa.Integer(), nullable=True)
    op.alter_column("messages", "body", existing_type=sa.Text(), nullable=True)

    op.create_table(
        "message_keys",
        sa.Column(
            "user_id",
            sa.Integer(),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        sa.Column("public_key", sa.Text(), nullable=False),
        sa.Column("wrapped_private_key", sa.Text(), nullable=False),
        sa.Column("salt", sa.String(length=64), nullable=False),
        sa.Column("wrap_iv", sa.String(length=32), nullable=False),
        sa.Column("key_check", sa.Text(), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
    )


def downgrade() -> None:
    op.drop_table("message_keys")
    op.execute("DELETE FROM messages")
    op.alter_column("messages", "body", existing_type=sa.Text(), nullable=False)
    op.alter_column("messages", "sender_id", existing_type=sa.Integer(), nullable=False)
    op.drop_column("messages", "iv")
    op.drop_column("messages", "ciphertext")
    op.drop_column("messages", "kind")
