# alembic/versions/zd3n4o5p6q7r8_promote_cms_customers_to_core.py
"""Promote CMS and Customers modules to core.

Revision ID: zd3n4o5p6q7r8
Revises: ze4o5p6q7r8s9
Create Date: 2026-01-27 10:10:00.000000

This migration ensures that CMS and Customers modules are enabled for all platforms,
since they are now core modules that cannot be disabled.
"""

from datetime import UTC, datetime

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "zd3n4o5p6q7r8"
down_revision = "ze4o5p6q7r8s9"
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Enable CMS and Customers modules for all platforms."""
    connection = op.get_bind()

    # Get all platform IDs
    platforms = connection.execute(
        sa.text("SELECT id FROM platforms")
    ).fetchall()

    now = datetime.now(UTC)
    core_modules = ["cms", "customers"]

    for (platform_id,) in platforms:
        for module_code in core_modules:
            # Check if record exists
            existing = connection.execute(
                sa.text(
                    """
                    SELECT id FROM platform_modules
                    WHERE platform_id = :platform_id AND module_code = :module_code
                    """
                ),
                {"platform_id": platform_id, "module_code": module_code},
            ).fetchone()

            if existing:
                # Update to enabled
                connection.execute(
                    sa.text(
                        """
                        UPDATE platform_modules
                        SET is_enabled = true, enabled_at = :now
                        WHERE platform_id = :platform_id AND module_code = :module_code
                        """
                    ),
                    {"platform_id": platform_id, "module_code": module_code, "now": now},
                )
            else:
                # Insert new enabled record
                connection.execute(
                    sa.text(
                        """
                        INSERT INTO platform_modules (platform_id, module_code, is_enabled, enabled_at, config)
                        VALUES (:platform_id, :module_code, true, :now, '{}')
                        """
                    ),
                    {"platform_id": platform_id, "module_code": module_code, "now": now},
                )

    # Note: JSON settings update skipped - platform_modules table is the primary
    # mechanism now. Legacy JSON settings will be handled by ModuleService fallback.


def downgrade() -> None:
    """
    Note: This doesn't actually disable CMS and Customers since that would
    break functionality. It just removes the explicit enabling done by upgrade.
    """
    # No-op: We don't want to disable core modules
