"""Add tenant_config JSONB column to tenants table.

Stores per-tenant feature flags and limits:
  max_concurrent_renders, render_engines_allowed, fallback_material,
  max_order_size, notifications_enabled, invoice_prefix.

Revision ID: 050
Revises: 049
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB

revision = "050"
down_revision = "049"
branch_labels = None
depends_on = None

_DEFAULT_CONFIG = """{
    "max_concurrent_renders": 3,
    "render_engines_allowed": ["cycles", "eevee"],
    "max_order_size": 500,
    "fallback_material": "SCHAEFFLER_059999_FailedMaterial",
    "notifications_enabled": true,
    "invoice_prefix": "INV"
}"""


def upgrade() -> None:
    op.add_column(
        "tenants",
        sa.Column(
            "tenant_config",
            JSONB,
            nullable=True,
            server_default=_DEFAULT_CONFIG,
        ),
    )
    # Backfill existing rows with defaults
    op.execute(
        f"UPDATE tenants SET tenant_config = '{_DEFAULT_CONFIG}'::jsonb WHERE tenant_config IS NULL"
    )


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