"""Wave 3: order_line as related records on order-management.

Header amount stays an explicit parent field — lines do not auto-sum.
No new Cloud jobs. checkout_app_block remains a coverage gap.

Revision ID: 159
Revises: 158
"""
from datetime import datetime, timezone

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

revision = "159"
down_revision = "158"
branch_labels = None
depends_on = None

feature_packs = sa.table(
    "feature_packs",
    sa.column("slug", sa.String),
    sa.column("composition", postgresql.JSONB),
    sa.column("version", sa.String),
    sa.column("updated_at", sa.DateTime(timezone=True)),
)


def _line_fields(parent_key: str, parent_entity: str) -> list[dict]:
    return [
        {
            "key": parent_key,
            "name": "Parent",
            "type": "relation",
            "relation_entity_key": parent_entity,
            "required": True,
            "indexed": True,
        },
        {"key": "description", "name": "Description", "type": "text", "required": True},
        {"key": "quantity", "name": "Quantity", "type": "number", "required": True},
        {"key": "unit_price", "name": "Unit price", "type": "number", "required": True},
        {"key": "notes", "name": "Notes", "type": "text"},
    ]


def order_lifecycle_v1_1() -> dict:
    from src.domain.feature_packs.crm_authorization import staff_policy
    from src.domain.feature_packs.normalize import stamp_composition

    policy = staff_policy()
    return stamp_composition(
        "order-management",
        {
            "function_slugs": [],
            "connector_actions": [],
            "requires": [],
            "entities": [
                {
                    "entity_key": "order_record",
                    "name": "Order",
                    "plural_name": "Orders",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": [
                            {"key": "reference", "name": "Reference", "type": "text", "required": True, "indexed": True},
                            {"key": "customer_name", "name": "Customer name", "type": "text"},
                            {"key": "customer_email", "name": "Customer email", "type": "text", "indexed": True},
                            {"key": "notes", "name": "Notes", "type": "text"},
                            {"key": "amount", "name": "Amount", "type": "number"},
                            {"key": "currency", "name": "Currency", "type": "text"},
                            {
                                "key": "status",
                                "name": "Status",
                                "type": "select",
                                "required": True,
                                "indexed": True,
                                "options": ["open", "fulfilled", "cancelled"],
                            },
                        ],
                        "access_policy": policy,
                    },
                },
                {
                    "entity_key": "order_line",
                    "name": "Order line",
                    "plural_name": "Order lines",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": _line_fields("order_record_id", "order_record"),
                        "access_policy": policy,
                    },
                },
            ],
        },
        implementation_version="1.1.0",
    )


def upgrade() -> None:
    conn = op.get_bind()
    now = datetime.now(timezone.utc)
    conn.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "order-management")
        .values(composition=order_lifecycle_v1_1(), version="1.1.0", updated_at=now)
    )


def downgrade() -> None:
    pass
