"""restrict partner service management permissions

Revision ID: 20260424_partner_service_restrictions
Revises: 20260423_services_phase_s2_default_templates
Create Date: 2026-04-24 20:00:00.000000
"""

from alembic import op
import sqlalchemy as sa

revision = "20260424_partner_service_restrictions"
down_revision = "20260423_services_phase_s2_default_templates"
branch_labels = None
depends_on = None

PARTNER_REMOVE_PERMISSIONS = (
    "services.create",
    "services.edit",
    "services.deactivate",
    "services.cross_branch",
    "services.import",
    "services.selection.manage",
    "service_tasks.create",
    "service_tasks.edit",
    "service_tasks.import",
    "service_tasks.deactivate",
)


def upgrade():
    conn = op.get_bind()
    conn.execute(
        sa.text(
            """
            DELETE FROM role_permissions
            WHERE role_id IN (SELECT id FROM roles WHERE name = :role_name)
              AND permission_id IN (SELECT id FROM permissions WHERE code IN :codes)
            """
        ).bindparams(sa.bindparam("codes", expanding=True)),
        {"role_name": "Partner", "codes": PARTNER_REMOVE_PERMISSIONS},
    )


def downgrade():
    conn = op.get_bind()
    rows = conn.execute(
        sa.text(
            """
            SELECT r.id AS role_id, p.id AS permission_id
            FROM roles r
            JOIN permissions p ON p.code IN :codes
            WHERE r.name = :role_name
            """
        ).bindparams(sa.bindparam("codes", expanding=True)),
        {"role_name": "Partner", "codes": PARTNER_REMOVE_PERMISSIONS},
    ).fetchall()

    for row in rows:
        exists = conn.execute(
            sa.text(
                """
                SELECT 1 FROM role_permissions
                WHERE role_id = :role_id AND permission_id = :permission_id
                """
            ),
            {"role_id": row.role_id, "permission_id": row.permission_id},
        ).fetchone()
        if not exists:
            conn.execute(
                sa.text(
                    """
                    INSERT INTO role_permissions (role_id, permission_id)
                    VALUES (:role_id, :permission_id)
                    """
                ),
                {"role_id": row.role_id, "permission_id": row.permission_id},
            )
