"""CLI tests for `flask create-admin`."""
from __future__ import annotations

from flask import Flask

from backend.app.auth import hash_password
from backend.app.extensions import db
from backend.app.models import User, UserRole


def test_create_admin_success(app: Flask) -> None:
    runner = app.test_cli_runner()
    result = runner.invoke(args=["create-admin", "alice", "p4ssw0rd"])
    assert result.exit_code == 0, result.output
    assert "created" in result.output.lower()
    user = User.query.filter_by(username="alice").first()
    assert user is not None
    assert user.role == UserRole.ADMIN


def test_create_admin_duplicate_username(app: Flask) -> None:
    existing = User(
        username="bob", password_hash=hash_password("originalpw"), role=UserRole.ADMIN
    )
    db.session.add(existing)
    db.session.commit()

    runner = app.test_cli_runner()
    result = runner.invoke(args=["create-admin", "bob", "anotherpw1"])
    assert result.exit_code != 0
    assert "exists" in (result.output + (result.stderr_bytes.decode() if result.stderr_bytes else "")).lower()


def test_create_admin_short_password(app: Flask) -> None:
    runner = app.test_cli_runner()
    result = runner.invoke(args=["create-admin", "charlie", "abc"])
    assert result.exit_code != 0
    combined = (result.output + (result.stderr_bytes.decode() if result.stderr_bytes else "")).lower()
    assert "8 characters" in combined
    assert User.query.filter_by(username="charlie").first() is None


def test_create_admin_missing_args(app: Flask) -> None:
    runner = app.test_cli_runner()
    result = runner.invoke(args=["create-admin"])
    # Click's UsageError exits with code 2
    assert result.exit_code != 0
