"""messaging v1.1.0: decouple from business_profile so classifieds (and anything else) can reuse it.

v1.0.0 tied conversation_membership/message to business_profile specifically
(my_business_record_id, sender_business_record_id as required relation fields) --
correct for BizConnect's B2B chat, wrong for a general-purpose messaging pack. A
classifieds site's buyers/sellers are plain signed-in users, not necessarily
business-directory profiles.

Renames those two fields to generic, OPTIONAL text fields (participant_ref /
sender_ref) -- real ownership/privacy was always enforced by the reserved
owner_user_id column via rls_enabled fan-out, never by these fields; they only ever
existed for display/domain-linkage. A project can still populate them with a
business_profile id (BizConnect), a classified_listing seller's own identity, or
leave them empty and resolve a display name from owner_user_id via GET
/auth/users/:id instead. No real installs exist yet (pack was seeded this same
session), so this is a clean rename, not a data migration.

Revision ID: 118
Revises: 117
"""
from datetime import datetime, timezone

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

revision = "118"
down_revision = "117"
branch_labels = None
depends_on = None

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

_CONVERSATION_MEMBERSHIP_V1_1 = {
    "entity_key": "conversation_membership",
    "name": "Conversation Membership",
    "plural_name": "Conversation Memberships",
    "rls_enabled": True,
    "schema": {
        "fields": [
            {"key": "conversation_id", "name": "Conversation ID", "type": "text", "required": True, "indexed": True},
            {
                "key": "participant_ref", "name": "Participant Reference", "type": "text", "indexed": True,
                "description": "Optional link to this project's own identity concept (e.g. a business_profile or classified_listing seller id). Ownership/privacy never depends on this field -- it is display-only.",
            },
            {"key": "other_participant_refs", "name": "Other Participants", "type": "json"},
            {"key": "title", "name": "Title", "type": "text"},
            {"key": "is_group", "name": "Is Group", "type": "boolean"},
            {"key": "last_message_at", "name": "Last Message At", "type": "date", "indexed": True},
        ],
    },
}

_MESSAGE_V1_1 = {
    "entity_key": "message",
    "name": "Message",
    "plural_name": "Messages",
    "rls_enabled": True,
    "schema": {
        "fields": [
            {"key": "conversation_id", "name": "Conversation ID", "type": "text", "required": True, "indexed": True},
            {
                "key": "sender_ref", "name": "Sender Reference", "type": "text", "indexed": True,
                "description": "Optional link to this project's own identity concept, same as conversation_membership.participant_ref. Display-only.",
            },
            {"key": "body", "name": "Body", "type": "text", "required": True},
            {"key": "read_at", "name": "Read At", "type": "date"},
        ],
    },
}

_CONVERSATION_MEMBERSHIP_V1_0 = {
    "entity_key": "conversation_membership",
    "name": "Conversation Membership",
    "plural_name": "Conversation Memberships",
    "rls_enabled": True,
    "schema": {
        "fields": [
            {"key": "conversation_id", "name": "Conversation ID", "type": "text", "required": True, "indexed": True},
            {
                "key": "my_business_record_id", "name": "My Business", "type": "relation",
                "relation_entity_key": "business_profile", "required": True, "indexed": True,
            },
            {"key": "participant_business_record_ids", "name": "Participants", "type": "json"},
            {"key": "title", "name": "Title", "type": "text"},
            {"key": "is_group", "name": "Is Group", "type": "boolean"},
            {"key": "last_message_at", "name": "Last Message At", "type": "date", "indexed": True},
        ],
    },
}

_MESSAGE_V1_0 = {
    "entity_key": "message",
    "name": "Message",
    "plural_name": "Messages",
    "rls_enabled": True,
    "schema": {
        "fields": [
            {"key": "conversation_id", "name": "Conversation ID", "type": "text", "required": True, "indexed": True},
            {
                "key": "sender_business_record_id", "name": "Sender Business", "type": "relation",
                "relation_entity_key": "business_profile", "required": True, "indexed": True,
            },
            {"key": "body", "name": "Body", "type": "text", "required": True},
            {"key": "read_at", "name": "Read At", "type": "date"},
        ],
    },
}

_COMPOSITION_V1_1 = {
    "function_slugs": [],
    "entities": [_CONVERSATION_MEMBERSHIP_V1_1, _MESSAGE_V1_1],
    "connector_actions": [],
    "requires": [],
}

_COMPOSITION_V1_0 = {
    "function_slugs": [],
    "entities": [_CONVERSATION_MEMBERSHIP_V1_0, _MESSAGE_V1_0],
    "connector_actions": [],
    "requires": [],
    "requires_packs": ["business-directory"],
}


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


def downgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "messaging")
        .values(version="1.0.0", composition=_COMPOSITION_V1_0, updated_at=datetime.now(timezone.utc))
    )
