"""first-run install wizard state

Revision ID: 0025_install_wizard
Revises: 0024_google_email_verified
Create Date: 2026-06-19

Adds app_state.configured + setup_token_hash for the first-run install wizard. Existing installs
(any users present) are marked configured so they never see the wizard; a genuinely fresh DB (no
users) starts unconfigured and boots into setup mode.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0025_install_wizard"
down_revision: Union[str, None] = "0024_google_email_verified"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        "app_state",
        sa.Column("configured", sa.Boolean(), nullable=False, server_default="false"),
    )
    op.add_column("app_state", sa.Column("setup_token_hash", sa.String(length=64), nullable=True))
    # Ensure the singleton row exists and mark it configured, then revert to unconfigured only if
    # this is a genuinely fresh DB (no users yet). Net: configured = (the instance already has users).
    op.execute(
        "INSERT INTO app_state (id, sync_paused, configured) VALUES (1, false, true) "
        "ON CONFLICT (id) DO UPDATE SET configured = true"
    )
    op.execute("UPDATE app_state SET configured = false WHERE NOT EXISTS (SELECT 1 FROM users)")


def downgrade() -> None:
    op.drop_column("app_state", "setup_token_hash")
    op.drop_column("app_state", "configured")
