"""fix_view_position_duplicates

Revision ID: 0255
Revises: 0254
Create Date: 2024-02-27 10:34:23.336692

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


# revision identifiers, used by Alembic.
revision = '0255'
down_revision = '0254'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        WITH project_ids_with_view_position_duplicates AS (
            SELECT DISTINCT v1.project_id AS id
            FROM views v1
            JOIN views v2 ON v2.position = v1.position AND v2.id != v1.id AND v1.project_id = v2.project_id
        ),
        positions AS (
            SELECT id, row_number() OVER (PARTITION BY project_id ORDER BY position) AS p
            FROM views
            WHERE views.project_id IN (SELECT id FROM project_ids_with_view_position_duplicates)
        ) UPDATE views SET position = positions.p - 1 FROM positions
        WHERE positions.id = views.id
    """)

    op.execute("""
        WITH user_ids_with_view_position_duplicates AS (
            SELECT DISTINCT v1.user_id AS id
            FROM views v1
            JOIN views v2 ON v2.position = v1.position AND v2.id != v1.id AND v1.user_id = v2.user_id AND v2.project_id IS NULL
            WHERE v1.project_id IS NULL
        ),
        positions AS (
            SELECT id, row_number() OVER (PARTITION BY user_id ORDER BY position) AS p
            FROM views
            WHERE views.project_id IS NULL AND views.user_id IN (SELECT id FROM user_ids_with_view_position_duplicates)
        ) UPDATE views SET position = positions.p - 1 FROM positions
        WHERE positions.id = views.id
    """)

def downgrade():
    pass
