"""Seed the initial feature-pack catalog: contact-capture, payment-checkout, salesforce-order-sync.

Revision ID: 099
Revises: 098
"""
from datetime import datetime, timezone
from uuid import uuid4

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

revision = "099"
down_revision = "098"
branch_labels = None
depends_on = None

feature_packs = sa.table(
    "feature_packs",
    sa.column("id", postgresql.UUID(as_uuid=True)),
    sa.column("slug", sa.String),
    sa.column("name", sa.String),
    sa.column("description", sa.Text),
    sa.column("version", sa.String),
    sa.column("tags", postgresql.JSONB),
    sa.column("status", sa.String),
    sa.column("composition", postgresql.JSONB),
    sa.column("input_schema", postgresql.JSONB),
    sa.column("access_policy", postgresql.JSONB),
)

_CONTACT_SUBMISSION_ENTITY = {
    "entity_key": "contact_submission",
    "name": "Contact Submission",
    "plural_name": "Contact Submissions",
    "schema": {
        "fields": [
            {"key": "name", "name": "Name", "type": "text", "required": True},
            {"key": "email", "name": "Email", "type": "text", "required": True, "indexed": True},
            {"key": "message", "name": "Message", "type": "text", "required": True},
            {"key": "status", "name": "Status", "type": "select",
             "options": ["received", "notified", "synced", "failed"], "indexed": True},
            {"key": "notify_error", "name": "Notify Error", "type": "text"},
        ],
    },
}

_PRODUCT_ENTITY = {
    "entity_key": "product",
    "name": "Product",
    "plural_name": "Products",
    "schema": {
        "fields": [
            {"key": "name", "name": "Name", "type": "text", "required": True},
            {"key": "description", "name": "Description", "type": "text"},
            {"key": "stripe_product_id", "name": "Stripe Product ID", "type": "text", "indexed": True},
        ],
    },
}

_PRICE_ENTITY = {
    "entity_key": "price",
    "name": "Price",
    "plural_name": "Prices",
    "schema": {
        "fields": [
            {"key": "product_record_id", "name": "Product", "type": "relation",
             "relation_entity_key": "product", "required": True, "indexed": True},
            # Source of trust for payment.checkout.create — the amount lives on Stripe's own
            # Price object, never re-derived from a caller-supplied number.
            {"key": "stripe_price_id", "name": "Stripe Price ID", "type": "text", "required": True, "indexed": True},
            {"key": "unit_amount", "name": "Unit Amount (display only)", "type": "number"},
            {"key": "currency", "name": "Currency (display only)", "type": "text"},
        ],
    },
}


def upgrade() -> None:
    now = datetime.now(timezone.utc)
    op.bulk_insert(
        feature_packs,
        [
            {
                "id": uuid4(),
                "slug": "contact-capture",
                "name": "Contact Capture",
                "description": (
                    "Validated contact-form submission with a durable inbox record, email "
                    "notification, and optional CRM sync — instead of a stateless forward."
                ),
                "version": "1.0.0",
                "tags": ["contact", "forms", "leads"],
                "status": "active",
                "composition": {
                    "function_slugs": [],
                    "entities": [_CONTACT_SUBMISSION_ENTITY],
                    "connector_actions": [],
                    "requires": [],
                },
                "input_schema": {
                    "type": "object",
                    "properties": {
                        "notify_email": {"type": "boolean", "default": True},
                        "crm_connector_action": {
                            "type": "string",
                            "description": "Optional connector action to upsert the submission as a CRM lead/contact, e.g. hubspot.upsert_contact.",
                        },
                    },
                },
                "access_policy": {"minimum_plan": "free"},
                "created_at": now,
                "updated_at": now,
            },
            {
                "id": uuid4(),
                "slug": "payment-checkout",
                "name": "Payment Checkout",
                "description": (
                    "Server-trusted Stripe checkout — resolves line-item prices from the "
                    "project's own price records instead of accepting client-supplied amounts."
                ),
                "version": "1.0.0",
                "tags": ["payments", "stripe", "checkout"],
                "status": "active",
                "composition": {
                    "function_slugs": [],
                    "entities": [_PRODUCT_ENTITY, _PRICE_ENTITY],
                    "connector_actions": ["payment.checkout.create", "stripe.create_checkout"],
                    "requires": ["stripe"],
                },
                "input_schema": {
                    "type": "object",
                    "properties": {},
                },
                "access_policy": {"minimum_plan": "free"},
                "created_at": now,
                "updated_at": now,
            },
            {
                "id": uuid4(),
                "slug": "salesforce-order-sync",
                "name": "Salesforce Order Sync",
                "description": (
                    "Recoverable order/line-item sync to Salesforce (standard Order object, a "
                    "custom object, or an Opportunity mapping) via retryable upsert-by-external-ID."
                ),
                "version": "1.0.0",
                "tags": ["salesforce", "crm", "orders"],
                "status": "active",
                "composition": {
                    "function_slugs": [],
                    "entities": [],
                    "connector_actions": ["salesforce.upsert_record"],
                    "requires": ["salesforce"],
                },
                "input_schema": {
                    "type": "object",
                    "properties": {
                        "target_object_type": {
                            "type": "string",
                            "description": "Salesforce object to sync orders into, e.g. Order, OrderItem, or a custom object API name.",
                            "default": "Order",
                        },
                        "external_id_field": {
                            "type": "string",
                            "description": "External ID field on the target object used for idempotent upsert.",
                        },
                    },
                },
                "access_policy": {"minimum_plan": "free"},
                "created_at": now,
                "updated_at": now,
            },
        ],
    )


def downgrade() -> None:
    op.execute(
        "DELETE FROM feature_packs WHERE slug IN "
        "('contact-capture', 'payment-checkout', 'salesforce-order-sync')"
    )
