"""add page_configs table

Revision ID: a1b2c3d4e5f6
Revises: f6d4a1b2c3e7
Create Date: 2026-02-10
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import text

revision = 'a1b2c3d4e5f6'
down_revision = 'f6d4a1b2c3e7'
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        'page_configs',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('post_id', sa.Integer(), nullable=False),
        sa.Column('features', sa.JSON(), server_default='{}', nullable=False),
        sa.Column('sumup_merchant_code', sa.String(64), nullable=True),
        sa.Column('sumup_api_key', sa.Text(), nullable=True),
        sa.Column('sumup_checkout_prefix', sa.String(64), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),
        sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('post_id'),
    )

    # Backfill: create PageConfig for every existing page
    conn = op.get_bind()

    # 1. Pages with calendars -> features={"calendar": true}
    conn.execute(text("""
        INSERT INTO page_configs (post_id, features, created_at, updated_at)
        SELECT p.id, '{"calendar": true}'::jsonb, now(), now()
        FROM posts p
        WHERE p.is_page = true
          AND p.deleted_at IS NULL
          AND EXISTS (
              SELECT 1 FROM calendars c
              WHERE c.post_id = p.id AND c.deleted_at IS NULL
          )
    """))

    # 2. Market page (slug='market', is_page=true) -> features={"market": true}
    #    Only if not already inserted above
    conn.execute(text("""
        INSERT INTO page_configs (post_id, features, created_at, updated_at)
        SELECT p.id, '{"market": true}'::jsonb, now(), now()
        FROM posts p
        WHERE p.slug = 'market'
          AND p.is_page = true
          AND p.deleted_at IS NULL
          AND p.id NOT IN (SELECT post_id FROM page_configs)
    """))

    # 3. All other pages -> features={}
    conn.execute(text("""
        INSERT INTO page_configs (post_id, features, created_at, updated_at)
        SELECT p.id, '{}'::jsonb, now(), now()
        FROM posts p
        WHERE p.is_page = true
          AND p.deleted_at IS NULL
          AND p.id NOT IN (SELECT post_id FROM page_configs)
    """))


def downgrade() -> None:
    op.drop_table('page_configs')
