"""user_favorites

Revision: 0235
Revision ID: 8abfd8e00867
Revises: 249b8b1c2bd6
Create Date: 2022-02-10 16:30:40.929731

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision = '8abfd8e00867'
down_revision = '249b8b1c2bd6'
branch_labels = None
depends_on = None


def upgrade():
    op.create_table('user_favorites',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('user_id', sa.Integer(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('object_type', sa.String(), nullable=False),
        sa.Column('object_id', sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_user_favorites_unique'), 'user_favorites', ['user_id', 'object_type', 'object_id'], unique=True)

    op.execute("""
        INSERT INTO user_favorites (user_id, object_type, object_id)
        SELECT DISTINCT users_pins.user_id, 'project', cards.project_id
        FROM cards
        JOIN users_pins ON users_pins.card_id = cards.id
        WHERE cards.parent_id IS NULL
    """)

    op.execute("""
        INSERT INTO user_favorites (user_id, object_type, object_id)
        SELECT DISTINCT users_pins.user_id, 'card', cards.id
        FROM cards
        JOIN users_pins ON users_pins.card_id = cards.id
        WHERE cards.parent_id IS NOT NULL
    """)


def downgrade():
    op.drop_table('user_favorites')
