"""Tests for migration 0010_server_live_state."""
from pathlib import Path

import sqlalchemy as sa
from alembic import command
from alembic.config import Config
from sqlalchemy import create_engine, inspect


_ALEMBIC_DIR = Path(__file__).resolve().parents[1] / "alembic"


def _alembic_config(db_url: str) -> Config:
    cfg = Config()
    cfg.set_main_option("script_location", str(_ALEMBIC_DIR))
    cfg.set_main_option("sqlalchemy.url", db_url)
    return cfg


def test_migration_0010_backfills_rcon_password(tmp_path: Path, monkeypatch) -> None:
    db_path = tmp_path / "t.db"
    db_url = f"sqlite:///{db_path}"
    monkeypatch.setenv("DATABASE_URL", db_url)

    cfg = _alembic_config(db_url)

    # Run alembic up to 0009 only.
    command.upgrade(cfg, "0009_user_password_changed_at")

    engine = create_engine(db_url)
    with engine.begin() as conn:
        conn.execute(sa.text(
            "INSERT INTO users (id, username, password_digest, admin, active, "
            "created_at, updated_at, password_changed_at) "
            "VALUES (1, 'u', 'x', 0, 1, '2026-01-01', '2026-01-01', '2026-01-01')"
        ))
        conn.execute(sa.text(
            "INSERT INTO blueprints (id, user_id, name, arguments, config, "
            "created_at, updated_at) "
            "VALUES (1, 1, 'bp', '[]', '[]', '2026-01-01', '2026-01-01')"
        ))
        conn.execute(sa.text(
            "INSERT INTO servers (id, user_id, blueprint_id, name, port, "
            "desired_state, actual_state, last_error, created_at, updated_at) "
            "VALUES (1, 1, 1, 's1', 27600, 'stopped', 'unknown', '', "
            "'2026-01-01', '2026-01-01')"
        ))
        conn.execute(sa.text(
            "INSERT INTO servers (id, user_id, blueprint_id, name, port, "
            "desired_state, actual_state, last_error, created_at, updated_at) "
            "VALUES (2, 1, 1, 's2', 27601, 'stopped', 'unknown', '', "
            "'2026-01-01', '2026-01-01')"
        ))

    # Apply migration 0010.
    command.upgrade(cfg, "0010_server_live_state")

    with engine.connect() as conn:
        rows = conn.execute(sa.text("SELECT id, rcon_password FROM servers ORDER BY id")).fetchall()

    assert len(rows) == 2
    for row in rows:
        assert len(row.rcon_password) >= 32
        assert row.rcon_password.replace("_", "").replace("-", "").isalnum()

    inspector = inspect(engine)
    assert "server_live_state" in inspector.get_table_names()
    assert "server_player_session" in inspector.get_table_names()
    assert "steam_user_profile" in inspector.get_table_names()
