"""add post user_id, author email, publish_requested

Revision ID: d4b2e8f1a3c7
Revises: c3a1f7b9d4e5
Create Date: 2026-02-08
"""
from alembic import op
import sqlalchemy as sa

revision = 'd4b2e8f1a3c7'
down_revision = 'c3a1f7b9d4e5'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add author.email
    op.add_column('authors', sa.Column('email', sa.String(255), nullable=True))

    # Add post.user_id FK
    op.add_column('posts', sa.Column('user_id', sa.Integer(), nullable=True))
    op.create_foreign_key('fk_posts_user_id', 'posts', 'users', ['user_id'], ['id'], ondelete='SET NULL')
    op.create_index('ix_posts_user_id', 'posts', ['user_id'])

    # Add post.publish_requested
    op.add_column('posts', sa.Column('publish_requested', sa.Boolean(), server_default='false', nullable=False))

    # Backfill: match posts to users via primary_author email
    op.execute("""
        UPDATE posts
        SET user_id = u.id
        FROM authors a
        JOIN users u ON lower(a.email) = lower(u.email)
        WHERE posts.primary_author_id = a.id
          AND posts.user_id IS NULL
          AND a.email IS NOT NULL
    """)


def downgrade() -> None:
    op.drop_column('posts', 'publish_requested')
    op.drop_index('ix_posts_user_id', table_name='posts')
    op.drop_constraint('fk_posts_user_id', 'posts', type_='foreignkey')
    op.drop_column('posts', 'user_id')
    op.drop_column('authors', 'email')
