"""Wave 2: quote_line, invoice_line, catalog_variant as related records.

Category is an indexed text field on catalog_item. Header amount/price stay
explicit parent fields — lines and variants do not auto-sum. No new Cloud jobs.

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

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

revision = "158"
down_revision = "157"
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 quote_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(
        "quote-lifecycle",
        {
            "function_slugs": [],
            "connector_actions": [],
            "requires": [],
            "entities": [
                {
                    "entity_key": "quote",
                    "name": "Quote",
                    "plural_name": "Quotes",
                    "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": "amount", "name": "Amount", "type": "number"},
                            {"key": "currency", "name": "Currency", "type": "text"},
                            {"key": "valid_until", "name": "Valid until", "type": "date"},
                            {"key": "notes", "name": "Notes", "type": "text"},
                            {
                                "key": "status",
                                "name": "Status",
                                "type": "select",
                                "required": True,
                                "indexed": True,
                                "options": ["draft", "sent", "accepted", "rejected", "expired"],
                            },
                        ],
                        "access_policy": policy,
                    },
                },
                {
                    "entity_key": "quote_line",
                    "name": "Quote line",
                    "plural_name": "Quote lines",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": _line_fields("quote_record_id", "quote"),
                        "access_policy": policy,
                    },
                },
            ],
        },
        implementation_version="1.1.0",
    )


def billing_management_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(
        "billing-management",
        {
            "function_slugs": [],
            "connector_actions": [],
            "requires": [],
            "entities": [
                {
                    "entity_key": "invoice_record",
                    "name": "Invoice",
                    "plural_name": "Invoices",
                    "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": "due_date", "name": "Due date", "type": "date"},
                            {
                                "key": "status",
                                "name": "Status",
                                "type": "select",
                                "required": True,
                                "indexed": True,
                                "options": ["draft", "issued", "paid", "void"],
                            },
                        ],
                        "access_policy": policy,
                    },
                },
                {
                    "entity_key": "invoice_line",
                    "name": "Invoice line",
                    "plural_name": "Invoice lines",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": _line_fields("invoice_record_id", "invoice_record"),
                        "access_policy": policy,
                    },
                },
            ],
        },
        implementation_version="1.1.0",
    )


def product_catalog_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(
        "product-catalog",
        {
            "function_slugs": [],
            "connector_actions": [],
            "requires": [],
            "entities": [
                {
                    "entity_key": "catalog_item",
                    "name": "Catalog item",
                    "plural_name": "Catalog items",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": [
                            {"key": "name", "name": "Name", "type": "text", "required": True},
                            {"key": "description", "name": "Description", "type": "text"},
                            {"key": "sku", "name": "SKU", "type": "text", "indexed": True},
                            {"key": "category", "name": "Category", "type": "text", "indexed": True},
                            {"key": "price_amount", "name": "Price", "type": "number"},
                            {"key": "currency", "name": "Currency", "type": "text"},
                            {
                                "key": "status",
                                "name": "Status",
                                "type": "select",
                                "required": True,
                                "indexed": True,
                                "options": ["active", "inactive"],
                            },
                        ],
                        "access_policy": policy,
                    },
                },
                {
                    "entity_key": "catalog_variant",
                    "name": "Catalog variant",
                    "plural_name": "Catalog variants",
                    "rls_enabled": False,
                    "owner_managed": False,
                    "schema": {
                        "fields": [
                            {
                                "key": "catalog_item_record_id",
                                "name": "Catalog item",
                                "type": "relation",
                                "relation_entity_key": "catalog_item",
                                "required": True,
                                "indexed": True,
                            },
                            {"key": "sku", "name": "SKU", "type": "text", "required": True, "indexed": True},
                            {"key": "name", "name": "Variant name", "type": "text", "required": True},
                            {"key": "price_amount", "name": "Price", "type": "number"},
                            {"key": "currency", "name": "Currency", "type": "text"},
                            {
                                "key": "status",
                                "name": "Status",
                                "type": "select",
                                "required": True,
                                "indexed": True,
                                "options": ["active", "inactive"],
                            },
                        ],
                        "access_policy": policy,
                    },
                },
            ],
        },
        implementation_version="1.1.0",
    )


def upgrade() -> None:
    conn = op.get_bind()
    now = datetime.now(timezone.utc)
    for slug, composition in (
        ("quote-lifecycle", quote_lifecycle_v1_1()),
        ("billing-management", billing_management_v1_1()),
        ("product-catalog", product_catalog_v1_1()),
    ):
        conn.execute(
            sa.update(feature_packs)
            .where(feature_packs.c.slug == slug)
            .values(composition=composition, version="1.1.0", updated_at=now)
        )


def downgrade() -> None:
    pass
