from collections.abc import Sequence
from pathlib import Path

import sqlalchemy as sa
from alembic import op


def get_revision() -> str:
    return Path(__file__).name.split("-")[0]


def get_down_revision() -> str | None:
    versions_path = Path(__file__).parent
    migration_files = sorted([f.name for f in versions_path.iterdir() if f.is_file()])
    for i, file in enumerate(migration_files):
        if file == Path(__file__).name:
            return None if i == 0 else migration_files[i - 1].split("-")[0]
    return None


# revision identifiers, used by Alembic.
revision: str = get_revision()
down_revision: str | None = get_down_revision()
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.add_column(
        "tenants",
        sa.Column(
            "allowed_m2m_metadata",
            sa.JSON,
            nullable=False,
            server_default="[]",
        ),
    )

    op.execute(
        """
        WITH aggregated_metadata AS (
            SELECT
                tenant_id,
                json_agg(
                    json_build_object(
                        'callerService', 'ctm',
                        'tenantName', name
                    )
                ) AS metadata
            FROM
                client_tenants
            GROUP BY
                tenant_id
        )
        UPDATE
            tenants
        SET
            allowed_m2m_metadata = aggregated_metadata.metadata
        FROM
            aggregated_metadata
        WHERE
            tenants.id = aggregated_metadata.tenant_id;
        """,
    )


def downgrade() -> None:
    op.drop_column("tenants", "allowed_m2m_metadata")
