"""Add team and organizational-unit records to the organization pack.

Revision ID: 166
Revises: 165
"""
from uuid import uuid4

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

revision = "166"
down_revision = "165"
branch_labels = None
depends_on = None


def _entity(key: str, name: str, plural: str) -> dict:
    return {
        "entity_key": key,
        "name": name,
        "plural_name": plural,
        "rls_enabled": False,
        "owner_managed": False,
        "schema": {
            "fields": [
                {"key": "name", "name": "Name", "type": "text", "required": True, "indexed": True},
                {"key": "organization_id", "name": "Organization", "type": "text", "indexed": True},
                {"key": "parent_id", "name": "Parent", "type": "text", "indexed": True},
                {"key": "description", "name": "Description", "type": "text"},
                {"key": "status", "name": "Status", "type": "select", "required": True, "indexed": True, "options": ["active", "inactive"]},
            ],
            "access_policy": {"authenticated": True, "ownership": "staff_managed", "required_roles": ["admin", "super_admin"]},
        },
    }


def upgrade() -> None:
    bind = op.get_bind()
    row = bind.execute(sa.text("SELECT composition FROM feature_packs WHERE slug='organization-records' FOR UPDATE")).mappings().first()
    if not row:
        return
    composition = dict(row["composition"] or {})
    entities = list(composition.get("entities") or [])
    keys = {item.get("entity_key") for item in entities if isinstance(item, dict)}
    for item in (_entity("team", "Team", "Teams"), _entity("org_unit", "Organizational Unit", "Organizational Units")):
        if item["entity_key"] not in keys:
            entities.append(item)
    composition["entities"] = entities
    statement = sa.text("UPDATE feature_packs SET composition=:composition, version='1.1.0' WHERE slug='organization-records'").bindparams(sa.bindparam("composition", type_=JSONB))
    bind.execute(statement, {"composition": composition})


def downgrade() -> None:
    pass
