"""Fix datasource password encryption stability

Revision ID: 002
Revises: 001
Create Date: 2026-04-23 14:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = "002"
down_revision: Union[str, None] = "001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Historical encrypted_password values are irrecoverable because
    # the old implementation generated a random Fernet key on every startup.
    # We clear the passwords and mark sources as inactive so admins re-enter them
    # with the new stable key derived from DB_ENCRYPTION_KEY / SECRET_KEY.
    op.add_column(
        "data_source",
        sa.Column("password_reset_required", sa.Boolean(), nullable=False, server_default=sa.text("false")),
    )
    op.execute(
        """
        UPDATE data_source
        SET encrypted_password = NULL,
            status = 'inactive',
            password_reset_required = true
        WHERE encrypted_password IS NOT NULL
        """
    )


def downgrade() -> None:
    op.drop_column("data_source", "password_reset_required")
