"""Phase v2.0.4-F - Platform SMTP settings

Revision ID: 20260620_phase_204f_platform_smtp
Revises: 20260619_phase_204e_year_lock_backup
Create Date: 2026-06-20
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260620_phase_204f_platform_smtp"
down_revision = "20260619_phase_204e_year_lock_backup"
branch_labels = None
depends_on = None


def _has_table(bind, table_name: str) -> bool:
    return sa.inspect(bind).has_table(table_name)


def _has_index(bind, table_name: str, index_name: str) -> bool:
    try:
        return any(idx.get("name") == index_name for idx in sa.inspect(bind).get_indexes(table_name))
    except Exception:
        return False


def upgrade() -> None:
    bind = op.get_bind()
    if not _has_table(bind, "platform_email_settings"):
        op.create_table(
            "platform_email_settings",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("smtp_host", sa.String(length=255), nullable=True),
            sa.Column("smtp_port", sa.Integer(), nullable=True),
            sa.Column("smtp_username", sa.String(length=255), nullable=True),
            sa.Column("smtp_password", sa.String(length=500), nullable=True),
            sa.Column("smtp_security", sa.String(length=20), nullable=False, server_default="SSL"),
            sa.Column("smtp_timeout_seconds", sa.Integer(), nullable=False, server_default="20"),
            sa.Column("from_email", sa.String(length=255), nullable=True),
            sa.Column("from_name", sa.String(length=255), nullable=True),
            sa.Column("reply_to_email", sa.String(length=255), nullable=True),
            sa.Column("send_auth_emails", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("updated_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        )
    if not _has_index(bind, "platform_email_settings", "ix_platform_email_settings_is_active"):
        op.create_index("ix_platform_email_settings_is_active", "platform_email_settings", ["is_active"])


def downgrade() -> None:
    bind = op.get_bind()
    if _has_table(bind, "platform_email_settings"):
        if _has_index(bind, "platform_email_settings", "ix_platform_email_settings_is_active"):
            op.drop_index("ix_platform_email_settings_is_active", table_name="platform_email_settings")
        op.drop_table("platform_email_settings")
