"""Add notification_preferences to users and email_digest_log table.

Revision ID: 029_add_email_digest
Revises: 028_add_shorts_template
"""

import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB, UUID

from alembic import op

revision = "029_add_email_digest"
down_revision = "028_add_shorts_template"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # notification_preferences JSONB on users
    op.add_column(
        "users",
        sa.Column(
            "notification_preferences",
            JSONB,
            nullable=False,
            server_default='{"email_digests": true, "digest_frequency": "daily"}',
        ),
    )

    # email_digest_log table
    op.create_table(
        "email_digest_log",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.func.gen_random_uuid()),
        sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("digest_sent_at", sa.DateTime, server_default=sa.func.now(), nullable=False),
        sa.Column("content_summary", JSONB, nullable=True),
    )
    op.create_index(
        "ix_email_digest_log_user_sent",
        "email_digest_log",
        ["user_id", "digest_sent_at"],
    )


def downgrade() -> None:
    op.drop_index("ix_email_digest_log_user_sent", table_name="email_digest_log")
    op.drop_table("email_digest_log")
    op.drop_column("users", "notification_preferences")
