"""Contact-capture uses platform email.send; Resend connector is no longer a prerequisite.

v1.2.0 still listed requires_connections: ["resend"] from the era when
contact-capture-notify called Resend directly. Notify/retry now enqueue
email.send, which Core authorizes against CLOUD_EMAIL_* (or a project BYOK
connector). Blocking pack install on a Resend connection meant generated
contact forms 502'd out of the box.

notify_to_email is no longer required in the catalog schema: PackInstallService
defaults it to the workspace owner email when omitted.

Revision ID: 126
Revises: 125
"""
from datetime import datetime, timezone

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

revision = "126"
down_revision = "125"
branch_labels = None
depends_on = None

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

_NOTIFY_STATIC_ENV = {
    "static_env_vars": {
        "NOTIFY_TO_EMAIL": "$config.notify_to_email",
        "SEND_CONFIRMATION_EMAIL": "$config.send_confirmation_email",
    }
}

_CRM_STATIC_ENV = {
    "static_env_vars": {
        "CRM_CONNECTION_ID": "$config.crm_connection_id",
        "CRM_CONNECTOR_ACTION": "$config.crm_connector_action",
        "CRM_FIELD_MAPPING": "$config.crm_field_mapping",
    }
}

_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", "indexed": True, "required": True},
            {"key": "message", "name": "Message", "type": "text", "required": True},
            {
                "key": "status", "name": "Status", "type": "select", "indexed": True,
                "options": ["received", "notified", "synced", "failed"],
            },
            {"key": "notify_error", "name": "Notify Error", "type": "text"},
            {"key": "notify_attempts", "name": "Notify Attempts", "type": "number", "indexed": True},
            {"key": "confirmation_sent", "name": "Confirmation Sent", "type": "boolean"},
            {
                "key": "crm_status", "name": "CRM Sync Status", "type": "select", "indexed": True,
                "options": ["not_configured", "pending", "failed"],
            },
            {"key": "crm_sync_error", "name": "CRM Sync Error", "type": "text"},
        ],
    },
}

_COMPOSITION_V1_3 = {
    "entities": [_ENTITY],
    "requires": [],
    "requires_connections": [],
    "connector_actions": [],
    "function_slugs": [
        {
            "library_slug": "contact-capture-notify",
            "project_slug": "contact-capture-notify",
            "trigger_config": {"event_type": "record.created", **_NOTIFY_STATIC_ENV},
        },
        {
            "library_slug": "contact-capture-crm-sync",
            "project_slug": "contact-capture-crm-sync",
            "trigger_config": {"event_type": "record.created", **_CRM_STATIC_ENV},
        },
        {
            "library_slug": "contact-capture-retry",
            "project_slug": "contact-capture-retry",
            "trigger_config": {"cron": "0 * * * *", **_NOTIFY_STATIC_ENV},
        },
    ],
}

_INPUT_SCHEMA_V1_3 = {
    "type": "object",
    "properties": {
        "notify_email": {
            "type": "boolean",
            "default": True,
            "description": "Send the site owner an email when a new submission arrives.",
        },
        "notify_to_email": {
            "type": "string",
            "description": (
                "Destination address(es) for new-submission notifications. "
                "Comma-separate multiple addresses. When omitted, the workspace owner email is used."
            ),
        },
        "send_confirmation_email": {
            "type": "boolean",
            "default": True,
            "description": "Send the visitor a confirmation email that their message was received.",
        },
        "crm_connection_id": {
            "type": "string",
            "description": "Optional connector connection id for a CRM to sync new submissions into.",
        },
        "crm_connector_action": {
            "type": "string",
            "enum": ["hubspot.upsert_contact", "salesforce.upsert_lead", "salesforce.upsert_contact"],
            "description": "Which CRM action to call. Required if crm_connection_id is set.",
        },
        "crm_field_mapping": {
            "type": "object",
            "description": "Maps contact_submission field names to CRM property/field names.",
        },
    },
}

_DESCRIPTION_V1_3 = (
    "Validated contact-form submission with a durable inbox record, owner email "
    "notification via platform email.send (no Resend connector required), optional "
    "visitor confirmation, and optional CRM upsert."
)

_COMPOSITION_V1_2 = {
    **_COMPOSITION_V1_3,
    "requires_connections": ["resend"],
}

_INPUT_SCHEMA_V1_2 = {
    **_INPUT_SCHEMA_V1_3,
    "required": ["notify_to_email"],
}


def upgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "contact-capture")
        .values(
            description=_DESCRIPTION_V1_3,
            version="1.3.0",
            composition=_COMPOSITION_V1_3,
            input_schema=_INPUT_SCHEMA_V1_3,
            updated_at=datetime.now(timezone.utc),
        )
    )


def downgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "contact-capture")
        .values(
            description=(
                "Validated contact-form submission with a durable inbox record, multi-recipient "
                "owner email notification with retry recovery, an optional visitor confirmation "
                "email, and optional real CRM upsert (HubSpot/Salesforce) via a connected "
                "connector action — instead of a stateless forward."
            ),
            version="1.2.0",
            composition=_COMPOSITION_V1_2,
            input_schema=_INPUT_SCHEMA_V1_2,
            updated_at=datetime.now(timezone.utc),
        )
    )
