"""add encrypted mail profiles and session csrf hashes

Revision ID: d3e4f5a6b7c8
Revises: c2d3e4f5a6b7
Create Date: 2026-06-16 11:00:00.000000
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "d3e4f5a6b7c8"
down_revision = "c2d3e4f5a6b7"
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    tables = set(inspector.get_table_names())
    if "access_auth_sessions" in tables:
        columns = {column["name"] for column in inspector.get_columns("access_auth_sessions")}
        if "csrf_token_hash" not in columns:
            op.add_column("access_auth_sessions", sa.Column("csrf_token_hash", sa.String(length=128), nullable=True))
    if "mail_server_profiles" not in tables:
        op.create_table(
            "mail_server_profiles",
            sa.Column("id", sa.String(length=36), nullable=False),
            sa.Column("tenant_id", sa.String(length=36), nullable=False),
            sa.Column("name", sa.String(length=255), nullable=False),
            sa.Column("slug", sa.String(length=100), nullable=False),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("is_active", sa.Boolean(), nullable=False),
            sa.Column("smtp_config", sa.JSON(), nullable=False),
            sa.Column("smtp_password_encrypted", sa.Text(), nullable=True),
            sa.Column("imap_config", sa.JSON(), nullable=True),
            sa.Column("imap_password_encrypted", sa.Text(), nullable=True),
            sa.Column("created_by_user_id", sa.String(length=36), nullable=True),
            sa.Column("updated_by_user_id", sa.String(length=36), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["access_users.id"], ondelete="SET NULL"),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenancy_tenants.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["access_users.id"], ondelete="SET NULL"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("tenant_id", "slug", name="uq_mail_server_profiles_tenant_slug"),
        )
        op.create_index(op.f("ix_mail_server_profiles_tenant_id"), "mail_server_profiles", ["tenant_id"])
        op.create_index(op.f("ix_mail_server_profiles_is_active"), "mail_server_profiles", ["is_active"])
        op.create_index(op.f("ix_mail_server_profiles_created_by_user_id"), "mail_server_profiles", ["created_by_user_id"])
        op.create_index(op.f("ix_mail_server_profiles_updated_by_user_id"), "mail_server_profiles", ["updated_by_user_id"])


def downgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    if "mail_server_profiles" in inspector.get_table_names():
        for name in (
            op.f("ix_mail_server_profiles_updated_by_user_id"),
            op.f("ix_mail_server_profiles_created_by_user_id"),
            op.f("ix_mail_server_profiles_is_active"),
            op.f("ix_mail_server_profiles_tenant_id"),
        ):
            try:
                op.drop_index(name, table_name="mail_server_profiles")
            except Exception:
                pass
        op.drop_table("mail_server_profiles")
    if "access_auth_sessions" in inspector.get_table_names():
        columns = {column["name"] for column in inspector.get_columns("access_auth_sessions")}
        if "csrf_token_hash" in columns:
            op.drop_column("access_auth_sessions", "csrf_token_hash")
