"""add environment config table

Revision ID: ddbf7bb95812
Revises: 0014
Create Date: 2026-02-22 20:32:58.070446

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'ddbf7bb95812'
down_revision: Union[str, None] = '0014'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """建立環境配置資料表"""

    # installation_environment_config (環境配置記錄)
    # 用途：記錄所有環境配置資訊，供初始化檢查使用
    op.create_table(
        'installation_environment_config',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('session_id', sa.Integer(), nullable=True),
        sa.Column('config_key', sa.String(100), nullable=False, unique=True),
        sa.Column('config_value', sa.Text(), nullable=True),
        sa.Column('config_category', sa.String(50), nullable=False),  # redis/database/keycloak/mailserver/nextcloud/traefik
        sa.Column('is_sensitive', sa.Boolean(), server_default='false'),
        sa.Column('is_configured', sa.Boolean(), server_default='false'),
        sa.Column('configured_at', sa.TIMESTAMP(), nullable=True),
        sa.Column('configured_by', sa.String(100), nullable=True),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('created_at', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP')),

        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['session_id'], ['installation_sessions.id'], ondelete='SET NULL')
    )

    op.create_index('idx_env_config_key', 'installation_environment_config', ['config_key'])
    op.create_index('idx_env_config_category', 'installation_environment_config', ['config_category'])
    op.create_index('idx_env_config_session', 'installation_environment_config', ['session_id'])


def downgrade() -> None:
    """移除環境配置資料表"""

    op.drop_index('idx_env_config_session', 'installation_environment_config')
    op.drop_index('idx_env_config_category', 'installation_environment_config')
    op.drop_index('idx_env_config_key', 'installation_environment_config')
    op.drop_table('installation_environment_config')
