"""Phase 7T.9 SSL automation status fields

Revision ID: 20260614_phase_7t9_ssl_automation
Revises: 20260613_phase_7t1_domain_mapping
Create Date: 2026-06-14
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260614_phase_7t9_ssl_automation"
down_revision = "20260613_phase_7t1_domain_mapping"
branch_labels = None
depends_on = None


def _table_exists(table_name: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return table_name in inspector.get_table_names()


def _column_exists(table_name: str, column_name: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    if table_name not in inspector.get_table_names():
        return False
    return column_name in {c["name"] for c in inspector.get_columns(table_name)}


def _add_column_if_missing(table_name: str, column: sa.Column) -> None:
    if not _column_exists(table_name, column.name):
        op.add_column(table_name, column)


def upgrade() -> None:
    if not _table_exists("domain_mappings"):
        return

    _add_column_if_missing("domain_mappings", sa.Column("ssl_status", sa.String(length=30), nullable=False, server_default="not_checked"))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_provider", sa.String(length=60), nullable=True))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_last_checked_at_utc", sa.DateTime(timezone=True), nullable=True))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_not_after_utc", sa.DateTime(timezone=True), nullable=True))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_issuer", sa.String(length=255), nullable=True))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_subject", sa.String(length=255), nullable=True))
    _add_column_if_missing("domain_mappings", sa.Column("ssl_last_error", sa.Text(), nullable=True))

    bind = op.get_bind()
    inspector = sa.inspect(bind)
    indexes = {idx["name"] for idx in inspector.get_indexes("domain_mappings")}
    if "ix_domain_mappings_ssl_status" not in indexes:
        op.create_index("ix_domain_mappings_ssl_status", "domain_mappings", ["ssl_status"], unique=False)


def downgrade() -> None:
    # SQLite-safe downgrade is intentionally conservative. Existing projects can keep
    # these nullable/status fields without affecting domain resolution.
    pass
